Skip to content

Instantly share code, notes, and snippets.

@Kruithne
Created July 15, 2013 17:26
Show Gist options
  • Save Kruithne/6001759 to your computer and use it in GitHub Desktop.
Save Kruithne/6001759 to your computer and use it in GitHub Desktop.
A simple static database wrapper using PDO in PHP.
<?php
class DB
{
/**
* @return PDO
*/
private static function getDB()
{
// The DATABASE_ constants here should be defined somewhere accessible to this wrapper.
if (self::$connection === null)
self::$connection = new PDO(DATABASE_DSN, DATABASE_USER, DATABASE_PASSWORD);
return self::$connection;
}
/**
* @param string $query
* @return PDOStatement
*/
public static function prepare($query)
{
return self::getDB()->prepare($query);
}
/**
* @param PDOStatement $query
* @return array
*/
public static function prepareObjects($query)
{
$return = Array();
while ($result = $query->fetchObject())
$return[] = $result;
return $return;
}
private static $connection;
}
// USAGE EXAMPLES
// Pulling data from a table.
$query = DB::prepare('SELECT email FROM users WHERE username = :user');
$query->bindValue(':user', 'johndoe552');
if ($query->execute())
{
while ($user = $query->fetchObject())
{
// Each time this loop iterates, $user will contain fields for a different row.
$email = $user->email;
}
}
// Inserting to a table.
$query = DB::prepare('INSERT INTO users (username, password, email) VALUES(:user, :pass, :email)');
$query->bindValue(':user', 'johndoe552');
$query->bindValue(':pass', 'sexyknockers'); // Obviously encryption is needed here.
$query->bindValue(':email', 'juicynibbles@hotmail.com');
$query->execute();
// Deleteing and getting delete count.
$query = DB::prepare('DELETE FROM users WHERE username = :baduser');
$query->bindValue(':baduser', 'Notch');
if ($query->execute())
echo sprintf('We deleted %s bad users.', $query->rowCount());
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment