PHP MySQL Connector Class

This class is basically the object-oriented version of MySQLi written with MySQL. It doesn't have any of the benefits of MySQLi, except that you can use the object-oriented approach. Since MySQLi has been released, I would highly recommend using that instead.

The code provided doesn't have every MySQL function available, but rather only the ones I used most often, however, it's easy to add new attributes or functions.

The Code

  1. <?php
  2. // database class
  3. // contains methods for connecting
  4. // and retrieving database stuff
  5.  
  6. class q_fns{
  7.    
  8.   public $query;
  9.   public $num_rows;
  10.      
  11.   public function __construct($s_sql){
  12.      
  13.     $this->query = mysql_query($s_sql);
  14.     $this->num_rows = @mysql_num_rows($this->query);
  15.        
  16.   }
  17.  
  18.   public function fetch_assoc(){
  19.      
  20.     return(mysql_fetch_assoc($this->query));
  21.        
  22.   }
  23.  
  24.   public function fetch_array(){
  25.  
  26.     return(mysql_fetch_array($this->query));
  27.    
  28.   }
  29.  
  30.   public function fetch_row(){
  31.  
  32.     return(mysql_fetch_row($this->query));
  33.    
  34.   }
  35.      
  36. }
  37.  
  38. class db_connect{
  39.   protected $host = "localhost";
  40.   protected $user = "username";
  41.   protected $pass = "password";
  42.   protected $data = "database";
  43.  
  44.   public function __construct(){
  45.  
  46.     $connect = mysql_connect($this->host, $this->user, $this->pass) or die("Couldn't connect to MySQL.\n" . mysql_error());
  47.     $dbpick = mysql_select_db($this->data, $connect) or die("Couldn't select MySQL database.\n" . mysql_error());
  48.    
  49.   }
  50.  
  51.   public function query($sql){
  52.    
  53.     return(new q_fns($sql));
  54.    
  55.   }
  56.  
  57. }
  58.  
  59. /*Implementation:
  60.  
  61. $mysql = new db_connect;
  62. $result = $mysql->query("select * from `table`");
  63. $num_rows = $result->num_rows;
  64. while($row = $result->fetch_assoc()){
  65.     echo $row['field'];
  66. }
  67.  
  68. */
  69.  
  70. ?>

The Download

Filename database.class.php
Filesize 1258 bytes
Filetype PHP Script
MD5 checksum 9821ca6a003a132d04a0047742b2eb74
License © 2007-2009 by Sculch, LLC. under the MIT License

Download Now

TAGS: PHP, MySQL