SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2002
    Posts
    75
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to use a class

    Hi,
    I have the following class for connecting to a mySQL database:

    PHP Code:
    <?php
    /**
    * Class for managing database connections
    *
    * Database class which affords easier management
    * of database connections and queries within your
    * php application, especially when utilising multiple
    * simultaneous queries and connections.

    * Public Methods:
    * DB::connect($host, $user, $pass, $db) - makes db connection
    * DB::pconnect($host, $user, $pass, $db) - makes a permanent db connection
    * DB::execute($query) - execute a SQL query
    * DB::fetch_all() - fetch results (numerical arrays within numerical array)
    * DB::fetch_all_assoc() - fetch results (assoc arrays within numerical array)
    * DB::fetch_all_obj() - fetch results (objects within numerical array)
    * DB::fetch_row() - fetch result row as numerical array
    * DB::fetch_assoc() - fetch result row as associative array
    * DB::fetch_obj() - fetch result row as an object
    * DB::db_close() - close database connection
    *
    * Examples:

    * Returning all rows as objects
    * <code>
    * $member = $myDB->fetch_all_obj();

    * // displaying results 
    * for ($i = 0, $end = sizeOf($member); $i <= $end; ++$i) {
    *     print $member[$i]->Member_Name;
    *     print "\n";
    * }
    * </code>
    *
    * Returning a single row as a numeric array and displaying
    * <code>
    * print_r($myDB->fetch_row());
    * </code>
    *
    * @author  Lloyd Roseblade <dbh@ski-info-online.com>
    * @access  public
    */
      
    class DB
      
    {
          
    /**
           * @return boolean
           * @param $host string
           * @param $user string
           * @param $pass string
           * @param $db string
           * @desc Public: Makes a database connection; returns true if connection is made, false if it fails;
           */
          
    function connect($host$user$pass$db)
          {          
              if (!
    $this->dbh = @mysql_connect($host$user$pass)) {
                  
    $this->_error();
                  return 
    false;
              }
            
              if (!@
    mysql_select_db($db)) {
                  
    $this->_error();
                  return 
    false;
              }
          }
          
    /**
           * @return boolean
           * @param $host string
           * @param $user string
           * @param $pass string
           * @param $db string
           * @desc Public: Makes a permanent database connection; returns true if connection is made, false if it fails;
           */
          
    function pconnect($host$user$pass$db)
          {          
              if (!
    $this->dbh = @mysql_connect($host$user$pass)) {
                  
    $this->_error();
                  return 
    false;
              }
            
              if (!@
    mysql_select_db($db)) {
                  
    $this->_error();
                  return 
    false;
              }
          }
          
    /**
           * @return boolean
           * @param $query string
           * @desc Public: Executes a SQL query; returns true if successful, false if not.
           */
          
    function execute($query$action null)
          {
              switch (
    $action) {
                  case 
    DISPLAY:
                      
    printf ("Executing [%s]\n"$query);
                      break;
                  default:
                      if (!
    $this->db_res = @mysql_query($query)) {
                          
    $this->_error($query);
                          return 
    false;
                      }
                      break;
              }
              return 
    true;
          }
          
    /**
           * @return array
           * @desc Public: Returns an array containing an array for each result row.
           */
          
    function fetch_all()
          {
              if (!
    $this->_checkResult()) die();
              
    $this->rows = array();
              while (
    $row $this->_fetch_row(DB_FETCH_NORM)) {
                  
    array_push($this->rows$row);
              }
              return 
    $this->rows;
          }
          
    /**
           * @return array
           * @desc Public: Returns an array containing an associative array for each result row.
           */
          
    function fetch_all_assoc() 
          {
              if (!
    $this->_checkResult()) die();
              
    $this->rows = array();
              if (!isset(
    $this->db_res)) {
                  
    $this->_error();
              }
              while (
    $row $this->_fetch_row(DB_FETCH_ASSOC)) {
                  
    array_push($this->rows$row);
              }
              return 
    $this->rows;
          }
          
    /**
           * @return array
           * @desc Public: Returns an array containing an object for each result row.
           */
          
    function fetch_all_obj() 
          {
              if (!
    $this->_checkResult()) die();
              
    $this->rows = array();
              while(
    $row $this->_fetch_row(DB_FETCH_OBJ)) {
                  
    array_push($this->rows$row);
              }
              return 
    $this->rows;
          }
          
    /**
           * @return integer
           * @desc Public: Returns number of rows returned from last query
           */
          
    function fetch_num_rows($res)
          {
              if (!
    $this->_checkResult()) die();
              return @
    mysql_num_rows($this->db_result);
          }
          
    /**
           * @return array
           * @desc Public: Fetch a result row as a numerical array.
           */
          
    function fetch_row()
          {
              if (!
    $this->_checkResult()) die();
              return 
    $this->_fetch_row(DB_FETCH_NORM);
          }
          
    /**
           * @return array
           * @desc Public: Fetch a result row as an associative array.
           */
          
    function fetch_assoc() 
          {
              if (!
    $this->_checkResult()) die();
              return 
    $this->_fetch_row(DB_FETCH_ASSOC);
          } 
          
    /**
           * @return array
           * @desc Public: Fetch a result row as an object.
           */
          
    function fetch_obj()
          {
              if (!
    $this->_checkResult()) die();
              return 
    $this->_fetch_row(DB_FETCH_OBJ);
          }
          
    /**
           * @return boolean
           * @desc Public: closes the database connection; returns true if successful, false if not
           */
          
    function db_close()
          {
              if (!
    mysql_close($this->dbh)) {
                  
    $this->_error();
                  return 
    false;
              }
              
              return 
    true;
          }
          
    /**
           * @return mixed
           * @param $mode string
           * @desc Private: fetches result set in chosen format (numerical or associative array, or object)
           */
          
    function _fetch_row($mode)
          {
              switch (
    $mode) {
                  case 
    DB_FETCH_NORM:
                      
    $this->row = @mysql_fetch_array($this->db_resMYSQL_NUM);
                      break;
                  case 
    DB_FETCH_ASSOC:
                      
    $this->row = @mysql_fetch_array($this->db_resMYSQL_ASSOC);
                      break;
                  case 
    DB_FETCH_OBJ:
                      
    $this->row = @mysql_fetch_object($this->db_res);
                      break;
              }
              
              return 
    $this->row;
          }
          
    /**
           * @return boolean
           * @desc Private: ensures a query result id is present; returns true if present, false if not
           */
          
    function _checkResult()
          {
              if (!isset(
    $this->db_res)) {
                  
    $this->_error();
                  return 
    false;
              }
              return 
    true;
          }
          function 
    getError($mode 'html')
          {
              
    $nl = ($mode == 'html') ? '<br />' "\n";
              
    $errMsg sprintf("Error executing query [%s]%sError No. [%s]%sError Message [%s]",
                                
    $this->_errQry$nl$this->_errNo$nl$this->_errStr);
              return 
    $errMsg;
          }
          
    /**
           * @return void
           * @desc Private: prints out the last error which occurred
           */
          
    function _error($query 'undefined')
          {          
              
    $this->_errQry $query;
              
    $this->_errNo  mysql_errno();
              
    $this->_errStr mysql_error();
              return 
    false;
          }
      } 
    // end DB class

    ?>
    The problem is I know little about working with classes and simply do not know how to use the above to pull out data out of a database. This is what I tried but I know it isn't right:

    PHP Code:
    <?
    include "mySQL.php.inc";
    $myDB = new DB;
     
    DB::connect(localhost, ****, *****, *****);

    $query "SELECT * FROM AP10_Field_Unit WHERE serial_number=0110";
    /*
    $member = $myDB->fetch_all_obj();
    for ($i = 0, $end = sizeOf($member); $i <= $end; ++$i) {
        print $member[$i]->serial_number;
        print "\n";
    }
    */
    $myDB->execute($query);

    //$myDB->fetch_assoc();
    while ($row $myDB->fetch_assoc()) {
        echo 
    "user_id: ".$row["serial_number"]."<br>\n";

    }
    echo 
    "test";
    ?>
    Can anyone please write a sample script for pulling out data?

  2. #2
    SitePoint Evangelist ClickHeRe's Avatar
    Join Date
    Mar 2005
    Location
    Ottawa, Canada
    Posts
    580
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    <?
    include "mySQL.php.inc";
    $myDB = new DB;
    
    $myDB->connect(localhost, ****, *****, *****);
    
    $query = "SELECT * FROM AP10_Field_Unit WHERE serial_number=0110";
    /*
    $member = $myDB->fetch_all_obj();
    for ($i = 0, $end = sizeOf($member); $i <= $end; ++$i) {
        print $member[$i]->serial_number;
        print "\n";
    }
    */
    $myDB->execute($query);
    
    //$myDB->fetch_assoc();
    while ($row = $myDB->fetch_assoc()) {
        echo "user_id: ".$row["serial_number"]."<br>\n";
    
    }
    echo "test";
    ?>
    David

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2002
    Posts
    75
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you, that helps a lot.

  4. #4
    SitePoint Enthusiast
    Join Date
    Oct 2002
    Posts
    75
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Instead of starting a new thread I figured I'll just post here. Any idea why this generates the following error:

    Code:
    Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$' in /home/jbiraaco/public_html/admin/add_db.php on line 14


    code:

    <STRONG>
    PHP Code:
     $query 'INSERT INTO customers (firstname, lastname, company, address, address2, city, state, zip, country, phone, fax, email, web, ssn) VALUES ("'.addslashes($_POST['firstname']).'", "'.addslashes($ _POST['lastname']).'", "'.addslashes($_POST['company']).'", "'.addslashes($_POST['address']).'", "'.addslashes($_POST['address2']).'", "'.addslashes($_POST['city']).'", "'.addslashes($_POST['state']).'", "'.addslashes($_POST['zip']).'", "'.addslashes($_POST['country']).'", "'.addslashes($_POST['phone']).'", "'.addslashes($_POST['fax']).'", "'.addslashes($_POST['email']).'", "'.addslashes($_POST['web']).'", "'.addslashes($_POST['ssn']).'"'

  5. #5
    SitePoint Wizard
    Join Date
    Jan 2004
    Location
    3rd rock from the sun
    Posts
    1,005
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You forgot to close the bracket at the end of the list of values:

    PHP Code:
    .........."'.addslashes($_POST['ssn']).'")'; 
    Though the error msg looks like a forgotten } bracket somewhere else to me.. try the above anyway


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •