PDO prepared statements and the elxisPDOStatement class
Elxis does extend use of prepared statements to execute queries to the database. Class elxisPDOStatement extends PDO's PDOStatement class providing some usefull methods like fetchAllAssoc and fetchPairs. The default fetch mode is PDO::FETCH_OBJ (fetch result sets as objects). There are 2 methods to prepare a statement, prepare without limit capabilities and prepareLimit with limit capabilities (PDO lucks limiting database results and so elxisDatabase fixes that). Both of these methods return an elxisPDOStatement instance.
Public methods
As elxisPDOStatement is an extension of PDOStatement it supports all PDOStatement methods plus some extra ones we have implemented into Elxis.
execute
Execute a prepared statement
public functionexecute($params=null, $options=array())
getQueryString
Get the query string
public functiongetQueryString()
fetchAllAssoc
Get result set as an associative array keyed by given field. Inspired by Drupal CMS (thanks guys).
public functionfetchAllAssoc($key, $fetchMode=null)
fetchPairs
Fetch a 2-column result set as an array of key-value pais.
public functionfetchPairs($key_index=0, $value_index=1)
fetchCol
Return single column as an indexed array.
public functionfetchCol($index = 0)
fetchResult
Fetch the value of the first column of the first row.
public functionfetchResult()
Examples
1. Prepared statements
// Prepare a statement without limit/offset (method prepare):
$db = eFactory::getDB();
$stmt = $db->prepare($sql, $options, $prefix);
// Prepare a statement with limit/offset (method prepareLimit):
// Get an array having as keys the category id (catid) and as values the category title. Limit the result to the first 5 rows and get only categories having as parent the category with catid = 2.
$parent = 2;
$sql = "SELECT catid, title FROM #__categories WHERE parent_id = :parent";