Easy usage of databases in PHP

When I started with development for PHP I did offend run into writing specific MySQL database code over and over in all my files. After suddenly running into something called Postegres SQL I quickly learned that this was not a good approach. I did also learn that it was really hard to debug database error with default error information, especially after the site was deployed for public usage.

So I decided to write the kill class that would solve all this small problems. The result was a simple database wrapper class container the most important functionality as:
– Connect
– Query
– Get next record in result (Perfect suited to be used with while loops)
– Get number of affected rows for SELECT, UPDATE, DELETE, INSERT
– Optimize table
– Clear result to free up memory
– Close connection
Get next record snippet

function next_record()
  $this->Record = mysql_fetch_array($this->Query_ID);
  $this->Errno = mysql_errno();
  $this->Error = mysql_error();
  $stat = is_array($this->Record);
  if (!$stat)
    $this->Query_ID = 0;
    $this->Row += 1;
  return $this->Record;

I also added some error handling that enable verbose error on the page during development mode and verbose error message with mail after deployment. The error result contains information as:
– General error message
– Error number and error text from the SQL server
– HTTP referrer
– Requested URI
– GET data
– POST data
And since I did use my class a lot for system with user authentication I did add user ID and user name for current user getting the error.

I hope this code will help someone out there to not end up with my problem and reinvent the wheel again.

MySQL version:db_inc.zip
PostrgressSQL version:db_inc_pg.zip

Usage example of the class

$db = new DB();
$db->query("SELECT * FROM Blog ORDER BY Date");
while($data = $db->next_record())
  $id = $data['ID']
  // Do more stuff