当进行相同的PDO查询(具有变化的参数)时,我是每次还是仅一次调用prepare()? [英] When making the same PDO query (with changing parameters), do I call prepare() every time, or just once?

查看:38
本文介绍了当进行相同的PDO查询(具有变化的参数)时,我是每次还是仅一次调用prepare()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何使用PDO,我需要帮助来了解一些内容.

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

我一直在读,使用PDO的最大好处之一是,当反复进行类似的查询时,它比mysql_*效率更高.我需要进行一个完全相同的查询,只是绑定参数每次都会更改(但是查询的结构是相同的).所以,这是我的问题:

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:

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

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?

谢谢!

推荐答案

文档右边:

为将使用不同参数值多次发出的语句调用PDO :: prepare()和PDOStatement :: execute(),通过允许驱动程序协商客户端和/或服务器端的缓存来优化应用程序性能.查询计划和元信息,并消除了手动引用参数的需要,从而有助于防止SQL注入攻击.

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.

因此,您只需要调用一次prepare并在循环内调用execute即可.

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

文档示例:

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

这篇关于当进行相同的PDO查询(具有变化的参数)时,我是每次还是仅一次调用prepare()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆