When making the same PDO query (with changing parameters), do I call prepare() every time, or just once?

删除回忆录丶 提交于 2019-12-11 03:52:10

问题


I'm trying to learn how to use PDO and I need help understanding something.

I keep reading that one of the biggest benefits of using PDO is that a it is much more efficient than mysql_* when making similar queries over and over again. I need to make a query that is exactly the same, except that the bound parameters change each time (but the structure of the query is the same). So, here's my question:

Should I call PDO::prepare() once and then inside my loop call execute() (passing the parameters array), or should I be calling PDO::preprare() every time the loop runs?

Thanks!


回答1:


Right out of the docs:

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

So you only call prepare once and call execute inside your loop.

Example out of docs:

<?php
/* Execute a prepared statement by passing an array of values */
$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();
?>

http://www.php.net/manual/de/pdo.prepare.php



来源:https://stackoverflow.com/questions/11484630/when-making-the-same-pdo-query-with-changing-parameters-do-i-call-prepare-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!