title: PHP: using the database class
body: <p>I have a class <code>Database</code> and Class <code>User</code>. My problem is that I want to create an instance of Database and use it throughout my classes.</p>
  
  <p>Class <code>User</code> is just one of them. I want to be able to get the user record from the table using the database object. I don't want to create a database variable inside each class, because I will using sessions. Is there a solution?</p>
  
  <pre><code>class Database
  {
      /*
       * Edit the following variables
       */
      private $db_host = 'localhost';     // Database Host
      private $db_user = 'root';          // Username
      private $db_pass = '';          // Password
      private $db_name = 'researchportal';          // Database
      /*
       * End edit
       */
  
      private $con = false;               // Checks to see if the connection is active
      private $result = array();          // Results that are returned from the query
  
      /*
       * Connects to the database, only one connection
       * allowed
       */
      public function connect()
      {
          if(!$this-&gt;con)
          {
              $myconn = @mysql_connect($this-&gt;db_host,$this-&gt;db_user,$this-&gt;db_pass);
              if($myconn)
              {
                  $seldb = @mysql_select_db($this-&gt;db_name,$myconn);
                  if($seldb)
                  {
                      $this-&gt;con = true;
                      return true;
                  }
                  else
                  {
                      return false;
                  }
              }
              else
              {
                  return false;
              }
          }
          else
          {
              return true;
          }
      }
  
      /*
      * Changes the new database, sets all current results
      * to null
      */
      public function setDatabase($name)
      {
          if($this-&gt;con)
          {
              if(@mysql_close())
              {
                  $this-&gt;con = false;
                  $this-&gt;results = null;
                  $this-&gt;db_name = $name;
                  $this-&gt;connect();
              }
          }
  
      }
  
      /*
      * Checks to see if the table exists when performing
      * queries
      */
      private function tableExists($table)
      {
          $tablesInDb = @mysql_query('SHOW TABLES FROM '.$this-&gt;db_name.' LIKE "'.$table.'"');
          if($tablesInDb)
          {
              if(mysql_num_rows($tablesInDb)==1)
              {
                  return true;
              }
              else
              {
                  return false;
              }
          }
      }
  
      /*
      * Selects information from the database.
      * Required: table (the name of the table)
      * Optional: rows (the columns requested, separated by commas)
      *           where (column = value as a string)
      *           order (column DIRECTION as a string)
      */
      public function select($table, $rows = '*', $where = null, $order = null)
      {
          $q = 'SELECT '.$rows.' FROM '.$table;
          if($where != null)
              $q .= ' WHERE '.$where;
          if($order != null)
              $q .= ' ORDER BY '.$order;
  
          $query = @mysql_query($q);
          if($query)
          {
              $this-&gt;numResults = mysql_num_rows($query);
              for($i = 0; $i &lt; $this-&gt;numResults; $i++)
              {
                  $r = mysql_fetch_array($query);
                  $key = array_keys($r);
                  for($x = 0; $x &lt; count($key); $x++)
                  {
                      // Sanitizes keys so only alphavalues are allowed
                      if(!is_int($key[$x]))
                      {
                          if(mysql_num_rows($query) &gt; 1)
                              $this-&gt;result[$i][$key[$x]] = $r[$key[$x]];
                          else if(mysql_num_rows($query) &lt; 1)
                              $this-&gt;result = null;
                          else
                              $this-&gt;result[$key[$x]] = $r[$key[$x]];
                      }
                  }
              }
              return true;
          }
          else
          {
              return false;
          }
      }
  
      /*
      * Insert values into the table
      * Required: table (the name of the table)
      *           values (the values to be inserted)
      * Optional: rows (if values don't match the number of rows)
      */
      public function insert($table,$values,$rows = null)
      {
          if($this-&gt;tableExists($table))
          {
              $insert = 'INSERT INTO '.$table;
              if($rows != null)
              {
                  $insert .= ' ('.$rows.')';
              }
  
              for($i = 0; $i &lt; count($values); $i++)
              {
                  if(is_string($values[$i]))
                      $values[$i] = '"'.$values[$i].'"';
              }
              $values = implode(',',$values);
              $insert .= ' VALUES ('.$values.')';
  
              $ins = @mysql_query($insert);
  
              if($ins)
              {
                  return true;
              }
              else
              {
                  return false;
              }
          }
      }
  
      /*
      * Deletes table or records where condition is true
      * Required: table (the name of the table)
      * Optional: where (condition [column =  value])
      */
      public function delete($table,$where = null)
      {
          if($this-&gt;tableExists($table))
          {
              if($where == null)
              {
                  $delete = 'DELETE '.$table;
              }
              else
              {
                  $delete = 'DELETE FROM '.$table.' WHERE '.$where;
              }
              $del = @mysql_query($delete);
  
              if($del)
              {
                  return true;
              }
              else
              {
                  return false;
              }
          }
          else
          {
              return false;
          }
      }
  
      /*
       * Updates the database with the values sent
       * Required: table (the name of the table to be updated
       *           rows (the rows/values in a key/value array
       *           where (the row/condition in an array (row,condition) )
       */
      public function update($table,$rows,$where)
      {
          if($this-&gt;tableExists($table))
          {
              // Parse the where values
              // even values (including 0) contain the where rows
              // odd values contain the clauses for the row
              for($i = 0; $i &lt; count($where); $i++)
              {
                  if($i%2 != 0)
                  {
                      if(is_string($where[$i]))
                      {
                          if(($i+1) != null)
                              $where[$i] = '"'.$where[$i].'" AND ';
                          else
                              $where[$i] = '"'.$where[$i].'"';
                      }
                  }
              }
              $where = implode('',$where);
  
  
              $update = 'UPDATE '.$table.' SET ';
              $keys = array_keys($rows);
              for($i = 0; $i &lt; count($rows); $i++)
              {
                  if(is_string($rows[$keys[$i]]))
                  {
                      $update .= $keys[$i].'="'.$rows[$keys[$i]].'"';
                  }
                  else
                  {
                      $update .= $keys[$i].'='.$rows[$keys[$i]];
                  }
  
                  // Parse to add commas
                  if($i != count($rows)-1)
                  {
                      $update .= ',';
                  }
              }
              $update .= ' WHERE '.$where;
              $query = @mysql_query($update);
              if($query)
              {
                  return true;
              }
              else
              {
                  return false;
              }
          }
          else
          {
              return false;
          }
      }
  
      /*
      * Returns the result set
      */
      public function getResult()
      {
          return $this-&gt;result;
      }
  }
  </code></pre>
  
  <p>Class User:</p>
  
  <pre><code>&lt;?php 
  require_once 'class.database.php';
  
      class User{
          public $usr_id;
          public $usr_name;
          public $usr_level;
          public $last_access_login;
  
          public function __construct($id) {
              $this-&gt;usr_id = $id;
              //$this-&gt;usr_name = $usr_name;
              //$this-&gt;usr_level = $usr_level;
              $this-&gt;last_access_login = date("F d Y H:i:s.",time());
        }
  
        public function getUser()
        {
      //  $db-&gt;select('login_users','*','user_id='.$this-&gt;usr_id.'');  
      //  $res = $db-&gt;getResult();  
      //  print_r($res);
  
          $this-&gt;usr_name = $res['username'];
          $this-&gt;usr_level = $res['user_level'];
          $this-&gt;last_access_login = date("F d Y H:i:s.",time());
  
        }
      }
  
      $a = new User(3);
      $a-&gt;getUser();
  
      ?&gt;
  </code></pre>