PDO::prepare
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::prepare — Подготавливает запрос к выполнению и возвращает ассоциированный с этим запросом объект
Описание
Подготавливает SQL запрос к базе данных к запуску посредством метода PDOStatement::execute(). Запрос может содержать именованные (:name) или неименованные (?) псевдопеременные, которые будут заменены реальными значениями во время запуска запроса на выполнение. Использовать одновременно и именованные, и неименованные псевдопеременные в одном запросе нельзя, необходимо выбрать что-то одно. Используйте псевдопеременные, чтобы привязать к запросу пользовательский ввод, не включайте данные, введенные пользователем, напрямую в запрос.
Вы должны подбирать уникальные имена псевдопеременных для каждого значение, которое необходимо передавать в запрос при вызове PDOStatement::execute(). Нельзя использовать одну псевдопеременную в запросе дважды. Также нельзя к одной именованной псевдопеременной привязать несколько значений, как например, в выражении IN() SQL запроса.
Вызов PDO::prepare() и PDOStatement::execute() для запросов, которые будут запускаться многократно с различными параметрами, повышает производительность приложения, так как позволяет драйверу кэшировать на клиенте и/или сервере план выполнения запроса и метаданные, а также помогает избежать SQL иньекций, так как нет необходимости экранировать передаваемые параметры.
Если драйвер не поддерживает подготавливаемые запросы, PDO умеет их эмулировать. Также, PDO может заменять псевдопеременные на то, что больше подходит, если, например, драйвер поддерживает только именованные или, наоборот, только неименованные маркеры.
Список параметров
-
statement
-
Это должен быть корректный запрос с точки зрения целевой СУБД.
-
driver_options
-
Этот массив содержит одну или более пар ключ=>значение для установки значений атрибутов объекта PDOStatement, который будет возвращен из этого метода. В основном, вы будете использовать этот массив для присвоения значения PDO::ATTR_CURSOR атрибуту PDO::CURSOR_SCROLL, чтобы получить прокручиваемый курсор. У некоторых драйверов могут быть свои специфические настройки, которые можно задать во время подготовки запроса.
Возвращаемые значения
Если СУБД успешно подготовила запрос,
PDO::prepare() возвращает объект
PDOStatement. Если подготовить запрос не удалось,
PDO::prepare() возвращает FALSE
или выбрасывает исключение
PDOException (зависит от текущего режима обработки ошибок).
Замечание:
Эмулируемые подготовленные запросы не создаются на сервере баз данных, поэтому PDO::prepare() не может проверить правильность построенного запроса.
Примеры
Пример #1 Подготовка SQL запроса с именованными параметрами
<?php
/* Выполнение запроса с передачей ему массива параметров */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>
Пример #2 Подготовка SQL запроса с неименованными параметрами (?)
<?php
/* Выполнение запроса с передачей ему массива параметров */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>
Смотрите также
- PDO::exec() - Запускает SQL запрос на выполнение и возвращает количество строк, задействованых в ходе его выполнения
- PDO::query() - Выполняет SQL запрос и возвращает результирующий набор в виде объекта PDOStatement
- PDOStatement::execute() - Запускает подготовленный запрос на выполнение
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Уровни абстракции
- Объекты данных PHP
- Функция PDO::beginTransaction() - Инициализация транзакции
- Функция PDO::commit() - Фиксирует транзакцию
- Функция PDO::__construct() - Создает экземпляр PDO, предоставляющий соединение с базой данных
- Функция PDO::errorCode() - Возвращает код SQLSTATE результата последней операции с базой данных
- PDO::errorInfo
- PDO::exec
- Функция PDO::getAttribute() - Получить атрибут соеденения с базой данных
- Функция PDO::getAvailableDrivers() - Возвращает массив доступных драйверов PDO
- Функция PDO::inTransaction() - Проверяет, есть ли внутри транзакция
- Функция PDO::lastInsertId() - Возвращает ID последней вставленной строки или последовательное значение
- PDO::prepare
- PDO::query
- Функция PDO::quote() - Заключает строку в кавычки для использования в запросе
- Функция PDO::rollBack() - Откат транзакции
- Функция PDO::setAttribute() - Присвоение атрибута
Коментарии
Attention using MySQL and prepared statements.
Using a placeholder multiple times inside a statement doesn't work. PDO just translates the first occurance und leaves the second one as is.
select id,name from demo_de where name LIKE :name OR name=:name
You have to use
select id,name from demo_de where name LIKE :name OR name=:name2
and bind name two times. I don't know if other databases (for example Oracle or MSSQL) support multiple occurances. If that's the fact, then the PDO behaviour for MySQL should be changed.
Using cursors doesn't work with SQLite 3.5.9. I get an error message when it gets to the execute() method.
Some of you might be saying "duh!" but i was surprised to see TRIGGER support in SQLite, so i had to try. :)
I wanted to use Absolute referencing on a Scrollable cursor and i only wanted one column of data. So i used this instead of a cursor.
<?php
$dbo = new PDO('sqlite:tdb');
$sql = 'SELECT F1, F2 FROM tblA WHERE F1 <> "A";';
$res = $dbo->prepare($sql);
$res->execute();
$resColumn = $res->fetchAll(PDO::FETCH_COLUMN, 0);
for($r=0;$r<=3;$r++)
echo 'Row '. $r . ' returned: ' . $resColumn[$r] . "\n";
$dbo = null;
$res = null;
?>
Note on the SQL injection properties of prepared statements.
Prepared statements only project you from SQL injection IF you use the bindParam or bindValue option.
For example if you have a table called users with two fields, username and email and someone updates their username you might run
UPDATE `users` SET `user`='$var'
where $var would be the user submitted text.
Now if you did
<?php
$a=new PDO("mysql:host=localhost;dbname=database;","root","");
$b=$a->prepare("UPDATE `users` SET user='$var'");
$b->execute();
?>
and the user had entered User', email='test for a test the injection would occur and the email would be updated to test as well as the user being updated to User.
Using bindParam as follows
<?php
$var="User', email='test";
$a=new PDO("mysql:host=localhost;dbname=database;","root","");
$b=$a->prepare("UPDATE `users` SET user=:var");
$b->bindParam(":var",$var);
$b->execute();
?>
The sql would be escaped and update the username to User', email='test'
You can also pass an array of values to PDOStatement::execute(). This is also secured against SQL injection. You don't necessarily have to use bindParam() or bindValue().
Maybe everyone else already knows this but...
If you have a routine that prepares/executes many insert or update statements for a sqlite db then you may want to make use of the pdo transactions.
On some old hardware my query set went from 12 seconds to 1/3-1/2 second.
-sean
Use prepared statements to ensure integrity of binary data during storage and retrieval. Escaping/quoting by f.e. sqlite_escape_string() or PDO::quote() is NOT suited for binary data - only for strings of text.
A simple test verifies perfect storage and retrieval with prepared statements:
<?php
$num_values = 10000;
$db = new pdo( 'sqlite::memory:' );
$db->exec( 'CREATE TABLE data (binary BLOB(512));' );
// generate plenty of troublesome, binary data
for( $i = 0; $i < $num_values; $i++ )
{
for( $val = null, $c = 0; $c < 512/16; $c++ )
$val .= md5( mt_rand(), true );
@$binary[] = $val;
}
// insert each value by prepared statement
for( $i = 0; $i < $num_values; $i++ )
$db->prepare( 'INSERT INTO data VALUES (?);' )->execute( array($binary[$i]) );
// fetch the entire row
$data = $db->query( 'SELECT binary FROM data;' )->fetchAll( PDO::FETCH_COLUMN );
// compare with original array, noting any mismatch
for( $i = 0; $i < $num_values; $i++ )
if( $data[$i] != $binary[$i] ) echo "[$i] mismatch\n";
$db = null;
?>
With PDO_MYSQL you need to remember about the PDO::ATTR_EMULATE_PREPARES option.
The default value is TRUE, like
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);
This means that no prepared statement is created with $dbh->prepare() call. With exec() call PDO replaces the placeholders with values itself and sends MySQL a generic query string.
The first consequence is that the call $dbh->prepare('garbage');
reports no error. You will get an SQL error during the $dbh->exec() call.
The second one is the SQL injection risk in special cases, like using a placeholder for the table name.
The reason for emulation is a poor performance of MySQL with prepared statements. Emulation works significantly faster.
Don't just automatically use prepare() for all of your queries.
If you are only submitting one query, using PDO::query() with PDO::quote() is much faster (about 3x faster in my test results with MySQL). A prepared query is only faster if you are submitting thousands of identical queries at once (with different data).
If you Google for performance comparisons you will find that this is generally consistently the case, or you can write some code and do your own comparison for your particular configuration and query scenario. But generally PDO::query() will always be faster except when submitting a large number of identical queries. Prepared queries do have the advantage of escaping the data for you, so you have to be sure to use quote() when using query().
Hi All,
First time posting to php.net, a little nervous.
After a bunch of searching I've learned 2 things about prepared statements:
1.) It fails if you enclose in a single quote (')
This fails: "SELECT * FROM users WHERE email=':email'"
This works: "SELECT * FROM users WHERE email=:email"
2.) You cannot search with a prepared statement
This fails: "SELECT * FROM users WHERE :search=:email"
This succeeds: "SELECT * FROM users WHERE $search=:email"
In my case I allow the user to enter their username or email, determine which they've entered and set $search to "username" or "email". As this value is not entered by the user there is no potential for SQL injection and thus safe to use as I have done.
Hope that saves someone else from a lot of searching.
To those wondering why adding quotes to around a placeholder is wrong, and why you can't use placeholders for table or column names:
There is a common misconception about how the placeholders in prepared statements work: they are not simply substituted in as (escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to "prepare" a statement comes up with a complete query plan for how it would execute that query, including which tables and indexes it would use, which will be the same regardless of how you fill in the placeholders.
The plan for "SELECT name FROM my_table WHERE id = :value" will be the same whatever you substitute for ":value", but the seemingly similar "SELECT name FROM :table WHERE id = :value" cannot be planned, because the DBMS has no idea what table you're actually going to select from.
Even when using "emulated prepares", PDO cannot let you use placeholders anywhere, because it would have to work out what you meant: does "Select :foo From some_table" mean ":foo" is going to be a column reference, or a literal string?
When your query is using a dynamic column reference, you should be explicitly white-listing the columns you know to exist on the table, e.g. using a switch statement with an exception thrown in the default: clause.
It is possible to prepare in advance several statements against a single connection. As long as that connection remains open the statements can be executed and fetched from as often as you like in any order; their "prepare-execute-fetch" steps can be interleaved in whichever way is best.
So if you're likely to be using several statements often (perhaps within a loop of transactions), you may like to consider preparing all the statements you'll be using up front.
Note that for Postgres, even though Postgres does support prepared statements, PHP's PDO driver NEVER sends the prepared statement to the Postgres server in advance of the call to PDO::execute().
Therefore, PDO::prepare() will never throw an error for things like faulty SQL syntax.
It also means the server will not parse and plan the SQL until the first time PDO::execute() is called, which may or may not adversely affect your optimization plans.
Noteworthy in my opinion is that if you prepare a statement but do not bind a value to the markers it will insert null by default. e.g.
<?php
/** @var PDO $db */
$prep = $db->prepare('INSERT INTO item(title, link) VALUES(:title, :link)');
$prep->execute();
?>
Will attempt to insert null, null into the item table.
if you run queries in a loop, don't include $pdo->prepare() inside the loop, it will save you some resources (and time).
prepare statement inside loop:
for($i=0; $i<1000; $i++) {
$rs = $pdo->prepare("SELECT `id` FROM `admins` WHERE `groupID` = :groupID AND `id` <> :id");
$rs->execute([':groupID' => $group, ':id' => $id]);
}
// took 0.066626071929932 microseconds
prepare statement outside loop:
$rs = $pdo->prepare("SELECT `id` FROM `admins` WHERE `groupID` = :groupID AND `id` <> :id");
for($i=0; $i<1000; $i++) {
$rs->execute([':groupID' => $group, ':id' => $id]);
}
// took 0.064448118209839 microseconds
for 1,000 (simple) queries it took 0.002 microseconds less.
not much, but it worth mention.
Many students are tempted to add single quotes around string place holders in the SQL statement, since that’s what they normally do around strings in SQL and PHP.
I have to explain:
Quotes are not part of the string — they are used to construct a string in the coding language. If you are creating a string literal in SQL or PHP, then it must indeed be quoted. If the string has already been created, and is being passed on, then additional quotes would be wrong at best, and mis-interpreted at worst.
In prepared place holders, think of place holders as variables, which, whether they are strings or other values, are always written without quotes.
Hello everyone.
I want to note that it doesn't matter where you are using a variable inside the query directly, that is not secure against SQL injections (unless performing a long security operation).
The following example is insecure against SQL injections:
<?php
$statement = $databaseConnection->prepare("SELECT * FROM `$_POST['table']` WHERE $_POST['search_for']=:search");
$statement->bindParam(":search", $search);
$search = 18; // For example
$statement->execute();
?>
If an attacker pass '1;-- ' as input named 'search_for', he is not a very bad attacker; because he didn't delete your data! In the above example, an attacker can do anything with connected database (unless you have restricted the connected user). Unfortunately, as Simon Le Pine mentioned, you cannot use prepared statements as other parts of a query; just can be used to search in indexes.
Hope this helps from loosing some data.
Sorry for my a bit weak English!
There are restrictions on the placeholder string. In the following code the first execute fails with a SQLSTATE[HY093]. It is not clear exactly what characters are allowed.
<?php declare(strict_types=1);
$db = new \PDO("mysql:hostname=localhost;dbname=minidwh", "minidwh", "Meisterstueck!");
$db->query("SET NAMES 'utf8mb4'");
$db->query("DROP TABLE IF EXISTS `äëïöüß`");
$db->query("CREATE TABLE `äëïöüß` ( `id` INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE = ARIA;");
$db->query("ALTER TABLE `äëïöüß` ADD COLUMN `äëïöüß` TEXT NULL");
try {
$stmt = $db->prepare("INSERT INTO `äëïöüß` (`äëïöüß`) VALUES (:äëïöüß)");
$result = $stmt->execute([':äëïöüß' => 'test1']);
} catch (\PDOException $e) {
echo $e->getMessage() . '<BR>';
}
try {
$stmt = $db->prepare("INSERT INTO `äëïöüß` (`äëïöüß`) VALUES (?)");
$result = $stmt->execute(['test2']);
} catch (\PDOException $e) {
echo $e->getMessage() . '<BR>';
}
try {
$stmt = $db->prepare("INSERT INTO `äëïöüß` (`äëïöüß`) VALUES (:column)");
$result = $stmt->execute([':column' => 'test3']);
} catch (\PDOException $e) {
echo $e->getMessage() . '<BR>';
}
try {
$stmt = $db->prepare("INSERT INTO `äëïöüß` (`äëïöüß`) VALUES (:column)");
$stmt->bindValue(':column', 'test4');
$result = $stmt->execute();
} catch (\PDOException $e) {
echo $e->getMessage() . '<BR>';
}