Archive

Archive for the ‘Developer Journal’ Category

Startups Find Talent with Games and Contests | Dice Blog Network

Building A PHP Database Connection Class From Scratch (using Singleton & ActiveRecord patterns)

April 8, 2012 11 comments

EH_DESIGN_2012.04.03_PhpMySQLLogo_07Greetings folks.

Tonight I’m studying on how to create a PHP Object-Oriented MySQL database connection class.  This will be reusable and able to be implemented in any database driven web application built with PHP & MySQL.  It uses the ActiveRecord and Singleton design patterns.

I’m currently following this YouTube tutorial: Using OOP PHP to select, update, and insert data in a mysql database. Nick Huot really does a superb job of explaining step-by-step, not only what he is doing, but also why.

(24 hrs later …)

So I am pleased to tell you, dear reader, about the successful PHP OOP Database Connection class I built last night, based on Huot’s tutorials — they really are the best I’ve seen.

I had a lot of debugging to do, but that was simple.  Nick had not provided all the code for PHP validating of variables and such.  I’m sure he would have but he probably ran short on time, so no worries.  The validations I came up with (making sure rows had values and were of type array, for instance), I have provided for you below in hopes it will save some of you some time.  If you choose to implement my code examples you may find that there are still validations I had not accounted for.  I’d love to hear of any bugs that you find, or improvements that you make on this example, or on your own projects derived from this code.

COMPLETE WORKING EXAMPLE:

config.php

<?php  
   // Database Constants
   define("DB_HOST", "localhost");
   define("DB_USER", "root");
   define("DB_PASS", "[your_db_pass]");
   define("DB_NAME", "[your_db_name]");
?>
database.class.php

<?php
require_once('../../viewutilities.php');

class database
{
   private $host;
   private $user;
   private $pass;
   private $dbName;
   
   private static $instance;
   
   private $connection;
   private $results;
   private $numRows; // optional
   
   private function __construct()
   {      
   }
   
   // singleton pattern
   static function getInstance()
   {
      if(!self::$instance)
      {
         self::$instance = new self();
      }
      return self::$instance;
   }
   
   function connect($host, $user, $pass, $dbName)
   {
      $this->host = $host;
      $this->user = $user;
      $this->pass = $pass;
      $this->dbName = $dbName;
      
      $this->connection = mysqli_connect($this->host,
                                         $this->user,
                                         $this->pass,
                                         $this->dbName);
   }
   
   public function doQuery($sql)
   {      
      $this->results = mysqli_query($this->connection, $sql);
      
      if ($this->results && $this->results->num_rows > 0) {
                  
         // NOTE: The line below was giving me this error:
         // "Trying to get property of non-object"
         //$this->numRows = $this->results->num_rows;
         
         $this->numRows = $this->results->num_rows;

      } // end if
   }
   
   public function loadObjectList()
   {
      $obj = "No Results";
            
      if ($this->results)
      {
         $obj = mysqli_fetch_assoc($this->results);
      }
      return $obj;
   }
   
} // end class

?>
table.class.php

<?php
require_once('../../viewutilities.php');

/**
 * Uses Active Record design pattern to implement a class that
 *  closely matches a given database table.  This class contains
 *  methods for binding the class members and methods to CRUD
 *  database management principles.  This type of class is sometimes
 *  referred to a "Table Model", and in many designs it is implemented
 *  as an abstract base class, which is then extended and specialized
 *  as necessary.
 */
class table
{
   protected $id = null;
   protected $table = null;
   
   function __construct()
   {
      
   }   
   
   /**
    * Takes assoc array as param $data.  Dynamically creates class properties
    *  with key as property name and value as its value.
    *
    * @param array $data key value pairs
    * @return
    * @access
    */
   function bind($data)
   {
      //print_r($data);
      foreach ($data as $key=>$value)
      {
         $this->$key = $value;
         //echo $key."--".$value;
      }
   }
   
   function load($id)
   {
      $this->id = $id;
      $dbo = database::getInstance();
      $sql = $this->buildQuery('load');
      
      $dbo->doQuery($sql);

      $row = $dbo->loadObjectList();
      
      if (isset($row) && is_array($row))
      {
         foreach ($row as $key=>$value)
         {
            if ($key == "id")
            {
               continue;
            }
            $this->$key = $value;            
         }               
      }

   }
   
   // write database object contents to database
   function store()
   {
      $dbo = database::getInstance();
      $sql = $this->buildQuery('store');
      $dbo->doQuery($sql);
   }
   
   protected function buildQuery($task)
   {
      $sql = "";
      if ($task == "store")
      {
         // if no id value has been store in this object yet,
         //  add new record to the database, else just update the record.
         if ($this->id == "")
         {
            $keys = "";
            $values = "";
            $classVars = get_class_vars(get_class($this));
            $sql .= "INSERT INTO {$this->table}";
            
            foreach ($classVars as $key=>$value)
            {
               if ($key == "id" || $key == "table")
               {
                  continue;
               }
               
               $keys .= "{$key},";
               $values .= "{$value},";
            }
            
            // NOTE: all substr($keys, 0, -1) does is gets rid of the comma
            // at the on the last array element.
            $sql .= "(".substr($keys, 0, -1).") Values (".substr($values, 0, -1).")";
            
         }else{
            
            $classVars = get_class_vars(get_class($this));
            $sql .= "UPDATE {$this->table} SET ";
            foreach ($classVars as $key=>$value)
            {
               if ($key == "id" || $key == "table")
               {
                  continue;
               }
               
               $sql .= "{$key} = '{$this->$key}'";
               
            }
            $sql .= substr($sql, 0, -2)." WHERE id = {$this->id}";
            
         }         
      }
      elseif ($task == "load")
      {
         $sql = "SELECT * FROM {$this->table} WHERE id = '{$this->id}'";
      }
      return $sql;      
   }
   
   
} // end class

?>
user.class.php

<?php
class user extends table
{
   var $fname = null;
   var $lname = null;
   var $email = null;
   var $table = "user";
}
?>
index.php

<?php
include('./database.class.php');
include('./table.class.php');
include('./user.class.php');

require_once('../../viewutilities.php');

// this has my connection constants
include('./config.php');

$dbo = database::getInstance();
$dbo->connect(DB_HOST, DB_USER, DB_PASS, 'testpatterns');
//$dbo->connect('localhost', 'root', '', 'testPatterns');

$user = new user();
$user->load('1');

echo "Name of user 1: {$user->fname} {$user->lname}<br />";
?>

Now in the interest of time, I’m publishing this post.  Soon I will add commentary and explanations and such, however, experienced Object-Oriented PHP developers will understand how to code fits together without explantion.  The best I can do for the newbies for now is to say if your database exists, has data matching the format the class is looking for , and is running you should be able to put all these files in your PHP Apache web directory (I’m using WAMP and on my system it is in C:\wamp\www; on yours it may be different), and launch index.php to see a first and last name pulled from one row of data, specified by id number, in your MySQL database.

Good luck, and I’d love to hear from you if you have questions, comments, or issues that you ran into.

– CodeSlayer2010

P.S.: Go ahead and comment out the requires and includes for “viewutilities.php”. If you don’t, the code will not work because it will complain that it can’t find this file.

I left it in there because I will be publishing it later on and you may find it useful debugging tool for your PHP scripts. This class is a wrapper for print_r() function and there are all kinds of advantages, the least of which is one line of code vs three with all your pre-tag. But this class and it’s static “debug” method streamline and simplify debugging complex AMP-stack PHP-based web applications. Watch for it soon!

Powershell – Executing commands which require quotes and variables is practically impossible!

March 30, 2012 4 comments


Executing commands which require quotes and variables is practically impossible: Microsoft Connect

This is an interesting forum thread about what I’ve spent the last 2 hours researching:  How to properly quote commands with parameters and interpolated paths so that they will execute as a command.  Doesn’t seem like it should be so hard.  Here is an example of the code I’m working with:

The command I’m trying to run:

C:\Program Files\Mozilla Firefox\firefox.exe -createprofile myTest

# Here is what works in MS-Dos / Windows XP command prompt:

"C:\Program Files\Mozilla Firefox\firefox.exe" -CreateProfile myTest

However, run the same thing in powershell and this is what you get:


PS C:\Documents and Settings\nunya> “C:\Program Files\Mozilla Firefox\firefox.exe” -CreatProfile myTest
You must provide a value expression on the right-hand side of the ‘-‘ operator.
At line:1 char:48Unexpected token ‘CreatProfile’ in expression or statement.
At line:1 char:49Unexpected token ‘myTest’ in expression or statement.
At line:1 char:62

Q & A: How To Schedule Publishing Of Multiple Posts in WordPress?

Hi folks,

I’ve been receiving some tech questions lately so I decided I’d start answering them on the blog so others can benefit as well.

Our next question is from Nadine in Houston, TX:

Question:

How do I schedule multiple posts in WordPress.com?  For instance, let’s say I want to make a queue or stack of posts, and the set up a rule that automatically publishes each post at certain intervals.  So, if I write 10 posts before going on vacation, I can set it up so that the next  one in the queue will publish itself to my blog every 3 days, or on some similar schedule.  I know you can schedule each post individually in WordPress.com by manually configuring the date on each post, but I’m looking for some automation to save time and do stuff in bulk.

Answer:

Great question Nadine.  Unfortunately, in WordPress.com you are only able to schedule posts one at a time.  On the other hand, if you self-host a WordPress.org-based blog then you have some more options.  One plugin that has high ratings is Editorial Calendar.  This gives you a calendar schedule view, you can schedule for multiple authors, drag and drop between days.  Overall, this one really gives you a lot of control options.  If you are hosting your own site, I’d say give it a try.

-Kristobaldude