Ultimate MySQL PDO Database Class for PHP

This database utility class is static (you do not need to create any type of object to use it) for easy of use, performance, and convenient code completion. All of the code is in a single file to make it incredibly easy to install and learn. It uses an internal global PDO database connection to make it easier to retrofit into existing projects or use in new projects.

I also made every effort to take care of all the details like: and using as little memory and being as lightweight as possible while still containing a lot of great features.

Some basic knowledge of how PDO "placeholders" work is helpful but not necessary. Every effort to use them is applied to stop SQL injection hacks and also because:

http://php.net/manual/en/pdo.prepare.php "There is a common misconception about how the placeholders in prepared statements work. They are not simply substituted in as (escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to "prepare" a statement comes up with a complete query plan for how it would execute that query, including which tables and indexes it would use."

Table of Contents

Connect

Connects to a MySQL PDO database.

First, you'll always want to connect to the database. There is no need to create an object or variable that points to the database. All of this is handled for you using an internal session variable.

DB::Connect($username, $password, $database, $hostname = 'localhost', $silent_errors = false)
If there is an error connecting, a string containing the error is returned. If there is no error, false is returned.
// Connect to the database $error = DB::Connect('appuser', 'pass123', 'production'); // If there was an error, stop and display it if ($error) die($error);
Back to top

Execute

Executes a SQL statement using PDO.

If you have a SQL statement that needs to be executed and doesn't return anything (usually an INSERT, UPDATE, or DELETE), use this method. Use DB::Insert, DB::Update, or DB::Delete if you are not using SQL (these methods automatically generate and execute SQL for you on the backend).

DB::Execute($sql, $placeholders = false, $debug = false)
The return result varies depending on the situation. If the SQL was an INSERT statement, the primary key of the record will be returned. Otherwise, if there was an error, false is returned. If the execution was sucessful, true is returned.
// Execute a SQL query // (FYI: You can also use DB::Safe() to return a safe quoted string for SQL) $sql = "INSERT INTO test_table (name, age, active) VALUES ('Sophia', 20, true)"; $id = DB::Execute($sql); // Execute a SQL query with placeholders (better because it stops SQL Injection hacks) $sql = 'DELETE FROM test_table WHERE name = :name AND age = :age AND active = :active'; $values = array('name' => 'Lucas', 'age' => 45, 'active' => true); $success = DB::Execute($sql, $values); // Execute the same SQL statement but only in debug mode // In debug mode, the record will not be saved $success = DB::Execute($sql, $values, true);
Back to top

Query

Executes a SQL statement using PDO and returns data as a multi-dimensional array.

If you have a SQL statement that returns records (usually a SELECT), use this method. Use DB::Select if you are not using or don't want to use SQL.

DB::Query($sql, $placeholders = false, $debug = false, $fetch_parameters = PDO::FETCH_ASSOC)
If there is an error executing the SQL, false is returned. Otherwise, the data is returned as a multi-dimensional array.
// Execute a SQL query to return an array containing all rows $sql = 'SELECT * FROM test_table'; $rows = DB::Query($sql); // Show the array print_r($rows); // Execute a SQL query using placeholders; this will return an array with all rows $sql = 'SELECT id, name, age FROM test_table WHERE active = :active'; $values = array('active' => true); $rows = DB::Query($sql, $values); // Execute the same query in debug mode $rows = DB::Query($sql, $values, true);
Back to top

QueryRow

Executes a SQL statement using PDO and returns a single row as an array.

Executes a SQL statement using PDO exactly the same way DB::Query does except only one row is returned. The syntax is identical. If more than more row would be returned by a given SQL query, using this method, only the first row would be returned. Don't forget to try setting debug mode to true.

DB::QueryRow($sql, $placeholders = false, $debug = false, $fetch_parameters = PDO::FETCH_ASSOC)
If there is an error executing the SQL, false is returned. Otherwise, the data is returned as an array.
// Execute a SQL query to return only one row $sql = 'SELECT * FROM test_table WHERE id = 1'; $row = DB::QueryRow($sql); // Show the array print_r($row);
Back to top

QueryValue

Executes a SQL statement using PDO and returns a single value.

Executes a SQL statement using PDO exactly the same way DB::Query does except only one value is returned. This is excellent for getting a single value like a name or a primary key. If more than more row or column would be returned by a given SQL query, using this method, only the first value on the first row would be returned.

DB::QueryValue($sql, $placeholders = false, $debug = false)
If there is an error executing the SQL, false is returned. Otherwise, the data is returned as a single value.
// Execute a SQL query to return only one value $sql = 'SELECT name FROM test_table WHERE id = 1'; $value = DB::QueryValue($sql); // Show the value echo $value;
Back to top

Select

Retrieves data from a specified table using PDO and returns data as a multi-dimensional array.

This is different from DB::Query because it does not require any SQL. If you need records from a single table, use this method.

DB::Select($table, $values = '*', $where = false, $order = false, $debug = false, $fetch_parameters = PDO::FETCH_ASSOC)
If there is an error retrieving the records, false is returned. Otherwise, the data is returned as a multi-dimensional array.
// Query records from a table $columns = array('id', 'name', 'age'); $where = array('active' => true); $rows = DB::Select('test_table', $columns, $where); // We can make more complex where clauses in the Select, Update, and Delete methods $columns = array('id', 'name', 'age'); $where = array( 'active IS NOT NULL', 'id >' => 10, 'UPPER(name) LIKE "%JEN%"' ); $rows = DB::Select('test_table', $columns, $where); // Let's sort by ID and run it in debug mode $rows = DB::Select('test_table', $columns, $where, 'id', true);
Back to top

SelectRow

Retrieves data from a specified table using PDO and returns a single row as an array.

Retrieves data the same way DB::Select does except only one row is returned. The syntax is nearly identical. If more than more row would be returned, using this method, only the first row would be returned.

This is different from DB::QueryRow because it does not require any SQL. If you need a single row from a table, use this method.

DB::SelectRow($table, $values = '*', $where = false, $debug = false, $fetch_parameters = PDO::FETCH_ASSOC)
If there is an error retrieving the records, false is returned. Otherwise, the data is returned as an associative array where the key is the field name.
// If only one row is needed, use the SelectRow method $rows = DB::SelectRow('test_table', 'name, age', 'id = 10');
Back to top

SelectValue

Retrieves data from a specified table using PDO and returns a single value.

Retrieves data the same way DB::Select does except only one value is returned. This is excellent for getting a single value like a name or a primary key. If more than more row or column would be returned, using this method, only the first value on the first row would be returned.

This is different from DB::QueryValue because it does not require any SQL. If you need a single value from the database, use this method.

DB::SelectValue($table, $field, $where = false, $debug = false)
If there is an error retrieving the records, false is returned. Otherwise, the data is returned as an associative array where the key is the field name.
// Grab one value - get the name of a person with ID 10 $value = DB::SelectRow('test_table', 'name', array('id' => 10));
Back to top

Insert

Inserts a new record into a table using PDO.

This method will insert a row into a table. Behind the scenes, this method actually generates and executes a SQL INSERT statement returning the primary key of the new row. No SQL is required using this method.

DB::Insert($table, $values, $debug = false)
If there is an error inserting the record, false is returned. Otherwise, the primary key is returned for the new row.
// Insert a new record $values = array('name' => 'Riley', 'age' => 30, 'active' => false); $success = DB::Insert('test_table', $values); // Try it in debug mode $success = DB::Insert('test_table', $values, true);
Back to top

Update

Updates an existing record into a table using PDO.

This method will update a row in a table. Behind the scenes, this method actually generates and executes a SQL UPDATE statement, but no SQL is required using this method.

DB::Update($table, $values, $where = false, $debug = false)
If there is an error updating a record, false is returned. Otherwise, true is returned on success.
// Update an existing record $update = array('age' => 35); $where = array('name' => 'Riley'); $success = DB::Update('test_table', $update, $where);
Back to top

Delete

Deletes a record from a table using PDO.

This method will delete a row in a table. Behind the scenes, this method actually generates and executes a SQL DELETE statement, but no SQL is required using this method.

DB::Delete($table, $where = false, $debug = false)
If there is an error deleting a record, false is returned. Otherwise, true is returned on success.
// Delete records $where = array('active' => false); $success = DB::Delete('test_table', $where);
Back to top

Transaction Processing

Allows for full transaction processing using PDO.

Transaction processing is used to maintain database integrity by ensuring that batches of MySQL operations execute completely or not at all.

Transaction processing is a mechanism used to manage sets of MySQL operations that must be executed in batches to ensure that databases never contain the results of partial operations. With transaction processing, you can ensure that sets of operations are not aborted mid-processing they either execute in their entirety or not at all (unless explicitly instructed otherwise). If no error occurs, the entire set of statements is committed (written) to the database tables. If an error does occur, a rollback (undo) can occur to restore the database to a known and safe state.

The key to managing transactions involves breaking your SQL statements into logical chunks and explicitly stating when data should be rolled back and when it should not.

NOTE: When using transaction processing, debugging mode will not rollback any inserts, updates, or deletes.

DB::TransactionBegin()
DB::TransactionCommit()
DB::TransactionRollback()

If there is an error, false is returned. Otherwise, true is returned on success.
// Begin a transaction DB::TransactionBegin() try { // Perform various actions on the database here // such as inserts, updates, and deletes // If success, commit and save the entire transaction DB::TransactionCommit() } catch (Exception $e) { // If there was a problem, rollback the transaction // as if no database actions here had ever happened DB::TransactionRollback() // Show the error var_dump($e->getMessage()); }
Back to top

ConvertQueryToSimpleArray

Converts the array results from a Query() or Select() into a simple array using only one column or an associative array using another column as a key.

This method is useful for converting a query into a key => value pair.

DB::ConvertQueryToSimpleArray($array, $value_field, $key_field = false)
This method will convert an array that looks like this:
$result = DB::Select('states', 'state_code, state_name'); print_r($result); Array ( [0] => Array ( [state_code] => AL [state_name] => Alabama ) [1] => Array ( [state_code] => AK [state_name] => Alaska ) [2] => Array ( [state_code] => AZ [state_name] => Arizona ) )
To an array that looks like this:
$array = DB::ConvertQueryToSimpleArray($result, 'state_name', 'state_code'); print_r($array); Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona )
Back to top

GetHTML

Executes a SQL statement using PDO and returns data as an HTML table.

This method generates HTML code.

DB::GetHTML($sql, $placeholders = false, $showCount = true, $styleTable = null, $styleHeader = null, $styleData = null)
If there is an error executing the SQL, false is returned. Otherwise, the data is returned as HTML.
$html = DB::GetHTML('SELECT * FROM test_table'); if ($html) { echo $html; } else { echo 'There was an error in your SQL.'; }
Back to top

EmptyToNull

Converts empty values to NULL.

This support function will return null for database calls if a variable is empty.

DB::EmptyToNull($value, $includeZero = true, $includeFalse = true, $includeBlankString = true)
Returns null if the value is empty, otherwise the original value is returned.
$values = array('amount' => DB::EmptyToNull($amount));
Back to top

Safe

Returns a quoted string using PDO that is safe to pass into an SQL statement.

This support function internally uses PDO::quote() to place quotes around an input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.

If you are using this function to build SQL statements, you are strongly recommended to use placeholders instead. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.

Not all PDO drivers implement this method (notably PDO_ODBC).

DB::Safe($value)
Returns a quoted value ready for SQL.
$values = array('name' => DB::Safe($name));
Back to top

ErrorEvent

This is an event function located at the top of the DB.php file that is called every time there is an error.

You can add code into this function (or override it when inheriting this class) to do things such as:

  1. Log errors into the database
  2. Send an email with the error message
  3. Save out to some type of log file
  4. Make a RESTful API call
  5. Run a script or program
  6. Set a session or global variable
  7. Or anything you might want to do when an error occurs
protected static function ErrorEvent($error, $error_code = 0)
This method does not return any value.

Back to top

Using Multiple Databases

When connecting to multiple databases, you can inherit the DB class and over-ride it's internal session variable.

You can create as many different connections as you need by inheriting from the base DB class and renaming the internal session variable constant name.

// Inherit the original DB class and over-ride // the internal session variable name class DBServer2 extends DB { const PDO_DB = 'db_server2'; } // Connect to the database $error = DBServer2::Connect('appuser', 'pass123', 'production');
Back to top