PHP - Performing queries via PHP Data Objects (PDO)

Introduction

To retrieve data from your database, use the query method.

This method accepts the query as a string and returns a list of rows as arrays.


$rows = $db->query('SELECT * FROM book ORDER BY title'); 
foreach ($rows as $row) { 
   var_dump($row); 
} 

PDO provides the exec function.

This function expects the first parameter as a string, defining the query to execute, but it returns a Boolean specifying whether the execution was successful or not.

A good example would be to try to insert books. Type the following:

$query = <<<SQL 
INSERT INTO book (isbn, title, author, price) 
VALUES ("9788187981954", "Peter Pan", "J. M. Barrie", 2.34) 
SQL; 
$result = $db->exec($query); 
var_dump($result); // true 

$query = <<<SQL 
INSERT INTO book (isbn, title, author, price) 
VALUES ("9788187981954", "Peter Pan", "J. M. Barrie", 2.34) 
SQL; 

$result = $db->exec($query);  
var_dump($result); // false 
$error = $db->errorInfo()[2]; 
var_dump($error); // Duplicate entry '9788187981954' for key 'isbn' 

Related Topic