Hi Guys,

Hi to everyone first...

Just wondering if anyone can help me with some examples or advice for programming in OOP.

I am trying to create a basic script that adds and removes entries from a database using classes.

I have read some tutorials / documents about programming in OOP, but I just cant get into my head how to structure it.

Hope some one can help and thanks in advance.

Kind Regards

Tony 😕

    It depends on how sophisticated you want to get, try this nice tutorial. If you have any specific questions let me know.

      a brief example

      
      class myClass {
      
        function doSomething() {
              // code fore doSomething()
       }
      
      }
      
      

      on another page

      require(myCLass.php);
      
      $newObject = new myClass();
      
      $newObject->doSomething();
      
      
      

        Hi,

        Thanks for the examples, but I understand how the classes work, but im a little confused on things such as mysql, should this be a seperate class. Then should I have a class called user which has functions of add, delete, update etc...

        so:

        class Users {
        
          function doAdd($username, $password, $email) {
                // code fore doAdd()
                // Adds the user details
         }
        
          function doRemove($user_id) {
                // code fore doRemove()
                // Removes the user details
         }
        
        }
        

        but then I want to add the user to a group, so I followed this through...

        I want to add the user, then choose a group for them to go into, if they select new group it goes through to an add groupo class, after this is done i want it to loop back round to the add user with the groups updated.

        Are you able to store the user details in the class, then call other functions in the class and then use the variables that were stored earlier?

        DSorry if this doesnt make much sence 😃

          Don't worry, It will make sense eventually. Do you want these variables to be available to other objects during execution? or in other pages? A very basic way of doing it, is to have a separate database class that would define the database connection as well as methods to connect to the database, this class will be instantiated from your main script, you could then call a function from that class to run your queries.

            Each class creates an object which can be manipulated in almost any way. You can define object-specific variables at the top of the class using the typical $something=''; syntax (or any other default value). Then you can use the $this-> keyphrase to refer to object specific variables. For example:

            class DB {
                $type='mysql';
                $conn=null;
                $user='';
                $pass='';
            
            public function setUser($user=null) {
                if($user===null) return false;
                $this->user = $user;
            }
            public function setPass($pass=null) {
                if($pass === null) return false;
                $this->pass = $pass;
            }
            public function connect() {
                if(($this->conn = mysql_connect('localhost', $this->user, $this->pass)) == false) return false;
                return true;
            }
            }

            Notice the $this-> keyphrase and how it modifies the "global" object variables?

            You could use a class to make the database an object; however, it's up to you. If you plan to support multiple database backends (mySQL, Postgres, Firebird, MSSQL) it would be a good idea that way you can have one database class and each specific type (say mysql) would extend that class with type-specific items (like connections or query optimization).

            Once an object is created, you can serialize it and store it in the session to go across pages, or across sessions and reuse it as if it was never gone 😉 But once an object is created, until it's destroyed (either by script / session end or manually destroyed), all object "global" variables (i.e. those referenced with $this-> ) are available to any member function (or method) of an object

              This is a work in progress, but should give you some food for thought. (Mainly I just need to decide how I want to handle various potential error situations.) This makes use of the singleton pattern.

              Mysql.class.php:

              <?php
              /**
              *  Mysql.class.php
              *  @author Charles Reace (www.charles-reace.com)
              *  @version 1.0
              *  @license http://opensource.org/licenses/gpl-license.php GNU Public License
              */
              
              /**
              *  class used for db query results
              */
              require_once 'QueryResult.class.php';
              
              /**
              *  "Singleton" pattern MySQL database class
              *  @package Database
              */
              class Mysql
              {
                 // USER MODIFIABLE DATABASE SETTINGS //
              
                 private $dbHost = 'localhost';
                 private $dbUser = 'dbuser';
                 private $dbPwd = 'password123';
                 private $database = 'database_name';
                 private $connx = NULL;
                 private $error = '';
              
                 // DO NOT MODIFY BELOW THIS LINE //
              
                 private static $instance;
              
                 /**
                 *  Private constructor: prevents direct creation of object
                 */
                 private function __construct()
                 {
                    $this->connect();
                 }
              
                 /**
                 *  Singleton method (only allow one instance of this class)
                 *  @return object
                 */
                 public static function singleton()
                 {
                    if (!isset(self::$instance)) 
                    {
                       $c = __CLASS__;
                       self::$instance = new $c;
                    }
              
                return self::$instance;
                 }  // end singleton()
              
                 /**
                 *  Prevent users from cloning this instance
                 *  @return void
                 */
                 public function __clone()
                 {
                    trigger_error('Clone is not allowed.', E_USER_ERROR);
                 }
              
                 /**
                 *  Connect to MySQL and select database
                 *  @return boolean
                 */
                 private function connect()
                 {
                    $connx = @mysql_connect($this->dbHost, $this->dbUser, $this->dbPwd);
                    if($connx != FALSE)
                    {
                       $this->connx = $connx;
                       $db = mysql_select_db($this->database, $this->connx);
                       if($db == FALSE)
                       {
                          $this->error = "Unable to select DB: " . mysql_error();
                          user_error($this->error, E_USER_WARNING);
                          return(FALSE);
                       }
                       return(TRUE);
                    }
                    $this->error = "Unable to connect to DBMS: " . mysql_error();
                    user_error($this->error, E_USER_WARNING);
                    return(FALSE);
                 }  // end connect()
              
                 /**
                 *  Get database connection resource ID
                 *  @return resource
                 */
                 public function getConnection()
                 {
                    return($this->connx);
                 }
              
                 /**
                 *  Sanitize input for use in SQL
                 *  @param string|integer|float $input
                 *  @return string|integer|float
                 */
                 public function sanitize($input)
                 {
                    $input = trim($input);
                    if(!is_numeric($input))
                    {
                       if(get_magic_quotes_gpc())
                       {
                          $input = stripslashes($input);
                       }
                       $input = "'" . mysql_real_escape_string($input) . "'";
                    }
                    return($input);
                 }
              
                 /**
                 *  Execute SELECT query (or any query that returns result rows)
                 *  @param string $sql
                 *  @return object
                 */
                 public function select($sql)
                 {
                    if(!$this->connx)
                    {
                       $this->error = "Cannot process query, no DB connection.";
                       user_error($this->error, E_USER_WARNING);
                       return(FALSE);
                    }
                    $result = mysql_query($sql, $this->connx);
                    if($result)
                    {
                       if(mysql_num_rows($result))
                       {
                          return(new QueryResult($result, $this->connx));
                       }
                       else
                       {
                          return(0);
                       }
                    }
                    else
                    {
                       $this->error = "Query failed ($sql): " . mysql_error();
                       user_error($this->error, E_USER_WARNING);
                       return(FALSE);
                    }
                 }
              
                 /**
                 *  Execute query that does not return result rows (e.g.: INSERT)
                 *  @param string $sql
                 *  @return integer
                 */
                 public function modify($sql)
                 {
                    if(!$this->connx)
                    {
                       $this->error = "Cannot process query, no DB connection.";
                       user_error($this->error, E_USER_WARNING);
                       return(FALSE);
                    }
                    $result = mysql_query($sql, $this->connx);
                    if($result)
                    {
                       return(mysql_affected_rows($this->connx));
                    }
                    else
                    {
                       $this->error = "Query failed ($sql): " . mysql_error();
                       user_error($this->error);
                       return(FALSE);
                    }
                 }
              }
              

              QueryResult.class.php:

              <?php
              /**
              *  Mysql.class.php
              *  @author Charles Reace (www.charles-reace.com)
              *  @version 1.0
              *  @license http://opensource.org/licenses/gpl-license.php GNU Public License
              */
              
              /**
              *  Query result from Mysql class
              *  @package Database
              */
              class QueryResult
              {
                 private $result = NULL;
                 private $connx = NULL;
                 private $numRows = 0;
              
                 /**
                 *  Constructor
                 *  @param resource $result
                 *  @param resource $connx
                 *  @return void
                 */
                 public function __construct($result, $connx)
                 {
                    $this->result = $result;
                    $this->connx = $connx;
                    $this->numRows = mysql_num_rows($result);
                 }
              
                 /**
                 *  Get specified result row as assoc. array
                 *  @param integer $row
                 *  @return array
                 */
                 public function getRow($row = NULL)
                 {
                    if($row !== NULL and is_numeric($row))
                    {
                       if(mysql_data_seek($this->result, abs((int)$row)))
                       {
                          return(mysql_fetch_assoc($this->result));
                       }
                    }
                    else
                    {
                       return(false);
                    }
                 }  // end getRow()
              
                 /**
                 *  Get query results as HTML table.
                 *  If $headers evaluates a TRUE, a header row will be included.
                 *  If $headers is TRUE and the $labels is an array, the values in $labels
                 *  will be used as the column heading labels.
                 *  @param boolean $headers
                 *  @param array $labels
                 *  @return string
                 */
                 public function getTable($headers = FALSE, $labels = NULL)
                 {
                    if(!mysql_data_seek($this->result, 0))
                    {
                       return(false);
                    }
                    $table = "<table class='dbresult'>\n";
                    if($headers)
                    {
                       $table .= "<tr>";
                       if(is_array($labels))
                       {
                          foreach($labels as $label)
                          {
                             $table .= "<th>$label</th>";
                          }
                       }
                       else
                       {
                          $num = mysql_num_fields($this->result);
                          for($ix = 0; $ix < $num; $ix++)
                          {
                             $table .= "<th>".mysql_field_name($this->result,$ix)."</th>";
                          }
                       }
                       $table .= "</tr>\n";
                    }
                    while($row = mysql_fetch_row($this->result))
                    {
                       $table .= "<tr>";
                       foreach($row as $val)
                       {
                          $table .= "<td>$val</td>";
                       }
                       $table .= "</tr>\n";
                    }
                    $table .= "</table>\n";
                    return($table);
                 }
              
                 /**
                 *  Get query results as an array
                 *  @return array
                 */
                 public function getArray()
                 {
                    mysql_data_seek($this->result, 0);
                    $data = array();
                    while($row = mysql_fetch_assoc($this->result))
                    {
                       $data[] = $row;
                    }
                    return($data);
                 }  // end getArray()
              
                 /**
                 *  Get query results as an XML string
                 *  @return string
                 */
                 public function getXml()
                 {
                    mysql_data_seek($this->result, 0);
                    $xml = "<?xml version='1.0' encoding='ISO-8859-1'?>\n<data>\n";
                    $count = 1;
                    while($row = mysql_fetch_assoc($this->result))
                    {
                       $xml .= "  <record row='$count'>\n";
                       foreach($row as $key => $val)
                       {
                          $xml .= "    <$key>$val</$key>\n";
                       }
                       $xml .= "  </record>\n";
                       $count++;
                    }
                    $xml .= "</data>";
                    return($xml);
                 }  // end getXml()
              
                 /**
                 *  Free this MySQL result
                 *  @return boolean
                 */
                 public function free()
                 {
                    return(mysql_free_result($this->result));
                 }  // end free()
              
                 /**
                 *  Getter for query result resource ID
                 *  @return resource
                 */
                 public function getResultId()
                 {
                    return($this->result);
                 }
              
                 /**
                 *  Getter for number of result rows
                 *  @return integer
                 */
                 public function getNumRows()
                 {
                    return($this->numRows);
                 }
              }  // end class QueryResult
              

              Sample usage:

              <?php
              ini_set('display_errors', 1);
              error_reporting(E_ALL);
              require_once 'Mysql.class.php';
              
              class Test
              {
                 private $db;
              
                 public function __construct()
                 {
                    $this->db = Mysql::singleton();
                 }
              
                 public function listCustomers()
                 {
                    $result = $this->db->select('SELECT * FROM customers');
                    return $result->getTable(true);
                 }
              }
              
              $test = new Test();
              echo $test->listCustomers();
              

                Could anyone explain why you would want to use classes instead of functions? To me, using functions seems easier, but maybe I'm missing some benefit the classes give?

                  There are many benefits to implementing Object Oriented Programming, one of its strong points is the ability to reuse code, but OOP goes beyond just reusing code, it introduces a programming model by which you can make your code more robust and much more extensible. Classes are the blue prints of objects and they are essential to OOP. With Php 5, the language introduced a strong object model that includes most of the featured of the more mature programming languages. I haven't been programming for too long, just about 4 month, but I have focused on OOP and so far I like what I see.

                    matt45 wrote:

                    Could anyone explain why you would want to use classes instead of functions? To me, using functions seems easier, but maybe I'm missing some benefit the classes give?

                    Classes are a tool designed for the implementation of object-oriented applications. (In actuality, you can create object-oriented applications without using classes, and you can use classes without creating an object-oriented application.) To understand their uses and benefits, you need to first understand what object-oriented programming is. A good place to start is this tutorial.

                      Hi Guys, thanks for the responce!

                      I know this may sound cheeky but I really learn better from looking at examples, does anyone have aqn example class that allows add / remove from a mysql database at all?

                      Thanks?

                        umm.... you mean like PDO or PEAR Database? Or many of the Database Abstraction Layers that you can find on Google?

                          I already gave you one.... if you only clicked that link....

                            Write a Reply...