gpt4 book ai didi

php - 当进行相同的 PDO 查询(改变参数)时,我是每次都调用 prepare() 还是只调用一次?

转载 作者:行者123 更新时间:2023-11-29 02:03:06 24 4
gpt4 key购买 nike

我正在尝试学习如何使用 PDO,但我需要帮助才能理解某些内容。

我一直在读到,使用 PDO 的最大好处之一是,在一遍又一遍地进行类似查询时,它比 mysql_* 更有效。我需要做一个完全相同的查询,除了绑定(bind)参数每次都改变(但查询的结构是相同的)。所以,这是我的问题:

我应该调用一次 PDO::prepare() 然后在我的循环中调用 execute()(传递参数数组),还是应该调用 PDO::preprare() 每次循环运行时?

谢谢!

最佳答案

就在文档之外:

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.

所以你只调用一次准备并在你的循环中调用执行。

文档外的例子:

<?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

关于php - 当进行相同的 PDO 查询(改变参数)时,我是每次都调用 prepare() 还是只调用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11484630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com