- PDO Querying Data
- Using the query() method to select data from a table
- Using a prepared statement to query data
- Summary
- Примеры использования PDO MySQL
- Подключение к серверу MySQL
- Выборка из БД
- Выборка одной записи
- Выборка всех записей таблицы
- Получить значение поля одной записи
- Получение всех значений одного столбца таблицы
- Получение структуры таблицы
- Добавление записей в БД
- Изменение записей
- Удаление из БД
- Обработка ошибок
- Комментарии 1
- PDO::query
- Parameters
- Return Values
- Errors/Exceptions
- Examples
- See Also
PDO Querying Data
Summary: in this tutorial, you will learn to query data from a table using PHP PDO using the query() method of the PDO object and a prepared statement.
To select data from a table using PDO, you can use:
When a query doesn’t have any parameters, you can use the query() method. For example:
SELECT * FROM publishers;
Code language: SQL (Structured Query Language) (sql)
However, if a query accepts one or more parameters, you should use a prepared statement for security reasons.
Using the query() method to select data from a table
To query data from a table using the query() method, you follow these steps:
The query() method returns a PDOStatement object. If an error occurs, the query() method returns false .
The following illustrates how to query all rows from the publishers table in the bookdb database:
$pdo = require 'connect.php'; $sql = 'SELECT publisher_id, name FROM publishers'; $statement = $pdo->query($sql); // get all publishers $publishers = $statement->fetchAll(PDO::FETCH_ASSOC); if ($publishers) < // show the publishers foreach ($publishers as $publisher) < echo $publisher['name'] . '
'; > >
Code language: HTML, XML (xml)
McGraw-Hill Education Penguin/Random House Hachette Book Group Harper Collins Simon and Schuster
When you use the PDO::FETCH_ASSOC mode, the PDOStatement returns an associative array of elements in which the key of each element is the column name of the result set.
First, create a database connection to the bookdb database:
$pdo = require 'connect.php';
Code language: PHP (php)
Second, define an SQL SELECT statement to select all rows from publishers table:
$sql = 'SELECT publisher_id, name FROM publishers';
Code language: PHP (php)
Third, run the query by calling the query() method of the PDO object:
$statement = $pdo->query($sql);
Code language: PHP (php)
Fourth, fetch all data from the result set:
$publishers = $statement->fetchAll(PDO::FETCH_ASSOC);
Code language: PHP (php)
The fetchAll() method with the PDO::FETCH_ASSOC option returns an associative array of data where:
- The keys are the names that appear on the select list
- and the values are the data rows in the result set.
Finally, iterate over the result set and show the array’s element:
// show the publishers if ($publishers) < foreach ($publishers as $publisher) < echo $publisher['name'] . '
'; > >
Code language: HTML, XML (xml)
Using a prepared statement to query data
The following example illustrates how to use a prepared statement to query data from a table:
$publisher_id = 1; // connect to the database and select the publisher $pdo = require 'connect.php'; $sql = 'SELECT publisher_id, name FROM publishers WHERE publisher_id = :publisher_id'; $statement = $pdo->prepare($sql); $statement->bindParam(':publisher_id', $publisher_id, PDO::PARAM_INT); $statement->execute(); $publisher = $statement->fetch(PDO::FETCH_ASSOC); if ($publisher) < echo $publisher['publisher_id'] . '.' . $publisher['name']; > else < echo "The publisher with id $publisher_id was not found."; >
Code language: HTML, XML (xml)
First, define a publisher id. In practice, you may get it from the query string:
$publisher_id = 1;
Code language: HTML, XML (xml)
Second, use the connect.php to connect to the bookdb database and return a new instance of the PDO object:
$pdo = require 'connect.php';
Code language: PHP (php)
Third, construct an SQL SELECT statement with a named placeholder ( :publisher_id )
$sql = 'SELECT publisher_id, name FROM publishers WHERE publisher_id = :publisher_id';
Code language: PHP (php)
Fourth, bind the value of the id to the prepared statement:
$statement->bindParam(':publisher_id', $publisher_id, PDO::PARAM_INT);
Code language: PHP (php)
Fifth, execute the prepared statement:
$statement->execute();
Code language: PHP (php)
Sixth, fetch a row from the result set into an associative array:
$publisher = $statement->fetch(PDO::FETCH_ASSOC);
Code language: PHP (php)
Finally, show the publisher information or an error message:
if ($publisher) < echo $publisher['publisher_id'] . '.' . $publisher['name']; > else < echo "The publisher with id $publisher_id was not found."; >
Code language: PHP (php)
Summary
- Use the query() method of an PDO object to execute a SELECT statement to query data from one or more tables.
Примеры использования PDO MySQL
Ниже приведены основные примеры работы с расширением PHP PDO. Такие как подключение к БД, получение, изменение и удаление данных. Подробнее о методах PDO можно узнать на php.net.
Для примеров используется таблица `category` с полями `id` , `name` и `parent` .
Подключение к серверу MySQL
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
Четвертым параметром конструктора PDO можно указать параметры подключения, например SQL запрос который будет выполнен сразу после подключения:
$dbh = new PDO(' mysql:dbname=db_name;host=localhost', 'логин', 'пароль', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'") );
Чтобы отследить ошибку подключения к БД используется исключение:
try < $dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль'); >catch (PDOException $e) < die($e->getMessage()); >
SQLSTATE[HY000] [1045] Access denied for user 'логин'@'localhost' (using password: YES)
Выборка из БД
Выборка одной записи
PDO позволяет использовать в запросах псевдопеременные чтобы исключить SQL инъекции. В самом запросе в место данных указывается ? или :id , а в методе execute() указываются реальные значения этих переменных.
$sth = $dbh->prepare("SELECT * FROM `category` WHERE `id` = ?"); $sth->execute(array('21')); $array = $sth->fetch(PDO::FETCH_ASSOC); print_r($array);
$sth = $dbh->prepare("SELECT * FROM `category` WHERE `id` = :id"); $sth->execute(array('id' => '21')); $array = $sth->fetch(PDO::FETCH_ASSOC); print_r($array);
Array ( [id] => 21 [parent] => 3 [name] => Хурма )
Выборка всех записей таблицы
Данный пример получает всю таблицу в виде ассоциативного массива:
$sth = $dbh->prepare("SELECT * FROM `category` ORDER BY `name`"); $sth->execute(); $array = $sth->fetchAll(PDO::FETCH_ASSOC); print_r($array);
Array ( [0] => Array ( [id] => 16 [parent] => 3 [name] => Абрикос ) [1] => Array ( [id] => 28 [parent] => 3 [name] => Авокадо ) . )
Получить значение поля одной записи
$sth = $dbh->prepare("SELECT `name` FROM `category` WHERE `id` = ?"); $sth->execute(array('21')); $value = $sth->fetch(PDO::FETCH_COLUMN); echo $value; // Выведет "Хурма"
Получение всех значений одного столбца таблицы
Пример получает все значения поля `name` из таблицы `category` .
$sth = $dbh->prepare("SELECT `name` FROM `category`"); $sth->execute(); $array = $sth->fetchAll(PDO::FETCH_COLUMN); print_r($array);
Array ( [0] => Мороженое [1] => Овощи [2] => Фрукты [3] => Ягоды [4] => Грибы [5] => Морепродукты [6] => Смеси . )
Получение структуры таблицы
$sth = $dbh->prepare("SHOW COLUMNS FROM `category`"); $sth->execute(); $array = $sth->fetchAll(PDO::FETCH_ASSOC); print_r($array);
Array ( [0] => Array ( [Field] => id [Type] => int(10) unsigned [Null] => NO New pdo php select => PRI [Default] => [Extra] => auto_increment ) [1] => Array ( [Field] => parent [Type] => int(11) unsigned [Null] => NO New pdo php select => [Default] => 0 [Extra] => ) [2] => Array ( [Field] => name [Type] => varchar(255) [Null] => NO New pdo php select => [Default] => [Extra] => ) )
Добавление записей в БД
$sth = $dbh->prepare("INSERT INTO `category` SET `parent` = :parent, `name` = :name"); $sth->execute(array('parent' => 1, 'name' => 'Виноград')); // Получаем id вставленной записи $insert_id = $dbh->lastInsertId();
Изменение записей
$sth = $dbh->prepare("UPDATE `category` SET `name` = :name WHERE `id` = :id"); $sth->execute(array('name' => 'Виноград', 'id' => 22));
Удаление из БД
$count = $dbh->exec("DELETE FROM `category` WHERE `parent` = 1"); echo 'Удалено ' . $count . ' строк.';
Или метод c псевдопеременными:
$sth = $dbh->prepare("DELETE FROM `category` WHERE `parent` = :parent"); $sth->execute(array('parent' => 1));
Обработка ошибок
В PDO есть метод errorInfo() который возвращает сведенья об ошибке последнего запроса.
// Таблицы `category_new` нет в БД. $sth = $dbh->prepare("INSERT INTO `category_new` SET `parent` = :parent, `name` = :name"); $sth->execute(array('parent' => 1, 'name' => 'Виноград')); $info = $sth->errorInfo(); print_r($info);
Array ( [0] => 42S02 [1] => 1146 [2] => Table 'database.category_new' doesn't exist )
Комментарии 1
О
Функция debugDumpParams объекта PDOStatement используется для вывода параметров подготовленного оператора. Это может быть полезно для отладки и устранения неполадок, поскольку позволяет увидеть точный SQL-запрос, который будет выполнен, а также значения любых установленных заполнителей.
Например, рассмотрим следующий код:
$sth = $dbh->prepare(‘SELECT * FROM users WHERE name = :name AND age = :age’);
$sth->bindParam(‘:name’, $name);
$sth->bindParam(‘:age’, $age);
$name = ‘John’;
$age = 35;
$sth->debugDumpParams();
SQL: [114] SELECT * FROM users WHERE name = :name AND age = :age
Params: 2
Key: Name: [5] :name
paramno=-1
name=[5] «:name»
is_param=1
param_type=2
Key: Name: [4] :age
paramno=-1
name=[4] «:age»
is_param=1
param_type=2
Вывод показывает SQL-запрос с заполнителями и значениями заполнителей (в данном случае :name — «John», а :age — 35). Это может быть полезно для проверки того, что в запросе используются правильные значения, или для выявления проблем с запросом или заполнителями.
Надеюсь, это поможет! Дайте знать, если у вас появятся вопросы.
Авторизуйтесь, чтобы добавить комментарий.
PDO::query
PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.
For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO::prepare() and issue the statement with multiple calls to PDOStatement::execute() .
If you do not fetch all of the data in a result set before issuing your next call to PDO::query() , your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query() .
Note:
If the query contains placeholders, the statement must be prepared and executed separately using PDO::prepare() and PDOStatement::execute() methods.
Parameters
The SQL statement to prepare and execute.
If the SQL contains placeholders, PDO::prepare() and PDOStatement::execute() must be used instead. Alternatively, the SQL can be prepared manually before calling PDO::query() , with the data properly formatted using PDO::quote() if the driver supports it.
The default fetch mode for the returned PDOStatement . It must be one of the PDO::FETCH_* constants.
If this argument is passed to the function, the remaining arguments will be treated as though PDOStatement::setFetchMode() was called on the resultant statement object. The subsequent arguments vary depending on the selected fetch mode.
Return Values
Returns a PDOStatement object or false on failure.
Errors/Exceptions
Emits an error with level E_WARNING if the attribute PDO::ATTR_ERRMODE is set to PDO::ERRMODE_WARNING .
Throws a PDOException if the attribute PDO::ATTR_ERRMODE is set to PDO::ERRMODE_EXCEPTION .
Examples
Example #1 SQL with no placeholders can be executed using PDO::query()
$sql = ‘SELECT name, color, calories FROM fruit ORDER BY name’ ;
foreach ( $conn -> query ( $sql ) as $row ) print $row [ ‘name’ ] . «\t» ;
print $row [ ‘color’ ] . «\t» ;
print $row [ ‘calories’ ] . «\n» ;
>
?>?php
The above example will output:
apple red 150 banana yellow 250 kiwi brown 75 lemon yellow 25 orange orange 300 pear green 150 watermelon pink 90
See Also
- PDO::exec() — Execute an SQL statement and return the number of affected rows
- PDO::prepare() — Prepares a statement for execution and returns a statement object
- PDOStatement::execute() — Executes a prepared statement