Valhalla Database Class
The code used by Valhalla for all database connections and queries to standardize connection handling and sanitation. Part of the valhalla-core-utils-lib (see demo link).
Check it out here: Demo Link
<?php /* * PDO SQL Database Class * Wrapper for the PDO driver * * @author ynori7 * @copyright Copyright (c) 2014, halls-of-valhalla.org * @license http://creativecommons.org/licenses/by-sa/4.0/ Creative Commons Attribution-ShareAlike 4.0 International License. * * This class must be extended by another class which should define the database name and connection information. * Usage: * Create a database class specific to your project: use Valhalla\CoreUtilities\Database\SQL\Pdo; class DAO extends Pdo { protected $_database; protected $_host = "localhost"; protected $_dbuser = "someone"; protected $_dbpass = "somepassword"; public function __construct($database='default'){ $this->_database = $database; $this->init(); } } * Next use your database class to query the database: $dao = new DAO('Users'); var_dump($dao->executeQuery('SELECT username FROM Users WHERE id=:id', array(':id' => 4))); * */ namespace Valhalla\CoreUtilities\Database\SQL; use \PDO as PdoBase; abstract class Pdo { /** * Database, Host, DbUser, and DbPass should be defined in a class extending this class. */ protected $_database; protected $_host; protected $_dbuser; protected $_dbpass; /** * @var PdoBase */ protected $_connection; /** * Creates a PdoBase instance. */ public function init() { $connection = new PdoBase("mysql:host={$this->_host};dbname={$this->_database};charset=utf8", $this->_dbuser, $this->_dbpass); $connection->exec("SET NAMES utf8"); $this->setConnection($connection); } /** * Executes $query bound with the specified $params using prepared statements. * * @param string $query The SQL query. * @param array $params Query params (optional) * @param boolean $debug Flag to indicate whether to dump the prepared statement. * @return array|boolean Array of results. False if unsuccessful. */ public function executeQuery($query, array $params = array(), $debug = false) { $result = false; $stmt = $this->getConnection()->prepare($query); if ($debug) { var_dump($stmt->debugDumpParams()); } if ($stmt->execute($params)) { $result = $stmt->fetchAll(PdoBase::FETCH_ASSOC); } return $result; } /** * Get error information for debugging purposes. * @return array */ public function getErrors() { return $this->getConnection()->errorInfo(); } /** * * @return PdoBase */ protected function getConnection() { return $this->_connection; } /** * * @param PdoBase $connection */ protected function setConnection($connection) { $this->_connection = $connection; } }

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Download this code in plain text format here