Here is what I use:
For more info on PDO see: http://php.net/manual/en/book.pdo.php
How to use:
//create connection
$connection = new Connection($settings,true);
$conn = $connection->conn;
//query
$sql = "SELECT StateName as State, StateAbbr as Abb FROM State";
$values = array(":Abbr" => "AL");
$query = new Query($conn);
$testArr = $query->getArrayFromQuery($sql, $values);
CONNECTION: (Connection.php)
class Connection
{
public $conn = null;
/**
* Creates PDO Database Connection
*
* @param array $params Connection Data (host,database,username,password)
* @param bool $useErrorReporting True to Show Errors (optional)
* @sets Database Connection
* @access public
*/
public function __construct($params,$useErrorReporting=false)
{
try
{
$host = "";
$database = "";
$username = "";
$password = "";
if(isset($params) && is_array($params))
{
$host = $params['database_connection']['host'];
$database = $params['database_connection']['database'];
$username = $params['database_connection']['username'];
$password = $params['database_connection']['password'];
$dsn = 'mysql:dbname='.$database.';host='.$host;
$dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => true));
//display errors if true
if($useErrorReporting)
{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
else
{
$dbh = null;
}
}
catch (PDOException $e)
{
throw new Exception('Connection Failed: '.$e->getMessage());
}
$this->conn = $dbh;
}
QUERY: Query.php
Class Query
{
private $conn = null;
/**
* sets query properties
*
* @param object $conn pdo connection object
* @return void
* @access public
*/
public function __construct($conn)
{
$this->conn = $conn;
}
/**
* getArrayFromQuery
* gets array from given query
*
* @param string $sql sql statement
* @param array $values array values to replace (":value" => 2)
* @return array
* @access public
*/
public function getArrayFromQuery($sql, $values)
{
$retValue = array();
$conn = $this->conn;
$statement = "";
try
{
//prepare sql statement
$statement = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
//add values
if(isset($values) && is_array($values))
{
$statement->execute($values);
}
//set return array to result array
$retValue = $statement->fetchAll();
}
catch (PDOException $e)
{
throw new Exception("PDO Query Error: ".$e->getMessage());
}
catch(Exception $e)
{
throw new Exception("Process Query Error: ". $e->getMessage());
}
return $retValue;
}
}