Examples of using PDO
Setting up a connection to MySQL:
try { $db = new PDO('mysql:host=localhost;dbname=testdb', $login, $passwd); } catch (PDOException $e) { echo $e->getMessage(); } // закрытия соединения и освобождение ресурсов $db = NULL;
connection with encoding consideration:
$db = new PDO('mysql:host=xxxx.ua;dbname=xxxx', $this->login, $this->passwd, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
PDO provides two ways to execute a query:
- preparing variables – recommended for speed && security
- direct execution
Queries that modify data are executed via the exec() method:
$db->exec(“INSERT INTO users (login) VALUES(‘john’)”); $id = $db->lastInsertId(); $db->exec(“UPDATE user SET login=‘alex’”)
The exec method returns a value – the number of affected rows, or FALSE in case of an error.
Queries that retrieve data are executed via the query() method:
$res = $db->query(“SELECT * FROM users”);
Returns FALSE in case of an error.
Escaping special characters (escaping values): $db->quote($_POST[‘login’])
Possible ways to fetch data:
- array (numeric or associative index)
- string (for a column)
- objects
- callback function
- lazy loading
- lazy loading
- iterators
Fetching an array:
$res = $db->query(“SELECT * FROM users”); while ($row = $res->fetch(PDO::FETCH_NUM)){ // $row - массив с числовыми ключами } $res = $db->query(“SELECT * FROM users”); while ($row = $res->fetch(PDO::FETCH_ASSOC)){ // $row - ассоциативный массив значений, ключи - названия столбцов } $res = $db->query(“SELECT * FROM users”); while ($row = $res->fetch(PDO::FETCH_BOTH)){ // $row - числовой и ассоиативный массив }
Fetching a single column:
$column = $db->query(“SELECT id FROM users WHERE login=‘login’ AND password=‘password’”); $user = $column->fetchColumn())
Fetching an object:
$res = $db->query(“SELECT * FROM users”); while ($obj = $res->fetch(PDO::FETCH_OBJ)) { // $obj - экземпляр объекта stdClass, имена столбцов - свойства объекта }
Fetching as an iterator (Iterator interface)
$res = $db->query(“SELECT * FROM users”, PDO::FETCH_ASSOC); foreach ($res as $row) { // $row - ассоциативный массив значений }
Lazy loading – returns the result as an object, but the actual population of the object with values occurs only upon the first access to that field:
$res = $db->query(“SELECT * FROM users”, PDO::FETCH_LAZY); foreach ($res as $row) { echo $row[‘name’]; // получение значения }
Retrieving all fetched values at once:
$qry = “SELECT * FROM users”; $res = $db->query($qry)->fetchAll(PDO::FETCH_ASSOC); // $res - массив всей выборки, каждая строка представлена ассоциативным массивом
Processing the fetch result with a callback function:
function add_salt($login,$passw) { … } $res = $db->query(“SELECT * FROM users”); $res->fetchAll(PDO::FETCH_FUNC, “add_salt”);
Capabilities of pre-prepared queries:
- compiled once, executed the required number of times
- clear separation between structure and input data (prevention of SQL injection)
- fast execution compared to query()/exec(), even for single execution
Example query:
$stmt = $db->prepare(“SELECT * FROM users WHERE id=?”); $stmt->execute(array($_GET[‘id’])); $stmt->fetch(PDO::FETCH_ASSOC);
Parameters for the query can be given by name and bound to variables:
$db->prepare('SELECT * FROM users WHERE name=:name AND email=:email'); $db->execute(array(':name'=>john,':email'=>'john@domain.com')); $result = $db->fetchAll(); print_r($result); $dbh->execute(array(':name'=>'alex',':email'=>'alex@domain.com')); print_r($result); // пример использования метода bindParam() try{ $sql = $db->prepare("INSERT INTO USERS(name,email) VALUES (:name,:email)"); $sql->bindParam(':name',$name); $sql->bindParam(':email',$email); // назначение значений и вставка новой строки $name='Joy'; $email='joy@domain.com'; $dbh->exec(); $name='debian'; $email='debian@domain.com'; $dbh->exec(); } catch(PDOException $e) { $dbh->rollBack(); echo 'Error : '.$e->getMessage(); }
Transactions. Almost all PDO drivers can work with transactions:
$db->beginTransaction(); if ($db->exec($qry) === FALSE) { $db->rollback(); } $db->commit();
Retrieving meta information about the query – number of columns and information about all columns:
$res = $db->query($qry); $ncols = $res->columnCount(); for ($i=0; $i < $ncols; $i++) { $meta_data = $res->getColumnMeta($i); }
Extending PDO capabilities:
class DB extends PDO { function query($qry, $mode=NULL) { $res = parent::query($qry, $mode); if (!$res) { var_dump($qry, $this->errorInfo()); return null; } else { return $res; } } }
