It seems in every new project I always need a few core components, one of which is a wrapper for some database functionality. Why a wrapper class? Why not just use the baked-in PHP commands? Well it’s generally helpful to abstract certain functionality, say if you wind up switching databases from mysql to postgres or postgres to oracle, you don’t necessarily want to rewrite every system call, especially since the syntax of the queries will probably be fairly similar. Also you may want to bolster error handling or extend the functionality of the native functions.
A real world example is PHP’s decision to phase out its mysql client in favor of mysqli and other variants. Using a wrapper class can take the pain out of such transitions.
Finding myself rewriting the same DB wrappers over and over again, I’m putting a fresh one up on Github with an MIT license (i.e. free for personal or commercial use). It’s pretty simple at this point, accepting only mysql and postgres as database types.
Download or fork it here: https://github.com/cbroome/PHP-DB-Class
Examples from the README file:
include 'db.php';
$db = new DB( 'mysql' );
if(!$db->connect('hostname', 'username', 'password', 'database') ) {
print "Could not connect! \n";
}
else {
$sql = "CREATE TEMPORARY TABLE temp_table( gallons INTEGER, galleons VARCHAR(255))";
if(!$db->query($sql)) {
print "Query failed: " . $db->get_error() . "\n";
}
else
{
print "Query succeeded!\n";
$value1 = $db->clean( "Should get an extra' character? " );
$value2 = $db->clean( "Imagine this off of a GET var: ';drop temp_table;#" );
$sql = "INSERT INTO temp_table(gallons, galleons) VALUES
(100, '$value1'),
(200, '$value2')";
print "Running query: \n" . $db->get_sql() . "\n";
if(!$db->query($sql))
{
print "Query failed: " . $db->get_error() . "\n";
}
else
{
print "Just ran: " . $db->get_sql() . "; Now let's see what was inserted: \n";
$sql = "SELECT * FROM temp_table";
if(!$db->query($sql)) {
print "Query failed: " . $db->get_error() . "\n";
}
else {
while( $row = $db->fetch_assoc()) {
print_r($row);
}
print "Finished \n";
}
}
}
}
Which results in:
$ php driver.php
Query succeeded!
Running query:
CREATE TEMPORARY TABLE temp_table( gallons INTEGER, galleons VARCHAR(255))
Just ran: INSERT INTO temp_table(gallons, galleons) VALUES
(100, 'Should get an extra\' character? '),
(200, 'Imagine this off of a GET var: \';drop temp_table;#'); Now let's see what was inserted:
Array
(
[gallons] => 100
[galleons] => Should get an extra' character?
)
Array
(
[gallons] => 200
[galleons] => Imagine this off of a GET var: ';drop temp_table;#
)
Finished