PHP PDO 准备语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1457131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP PDO prepared statements
提问by Hanpan
I was told today that I should really be using PDO and prepared statements in my application. Whilst I understand the benefits, I am struggling to understand how I implement them into my workflow. Aside from the fact that it makes code much cleaner, should I have a specific database class which houses all my prepared statements or should I create one each time I want to run a query? I'm finding it very hard to understand when I should use a standard PDO query and when I should use a prepared statement. Any examples, tips or tutorial links would be greatly appreciated.
今天有人告诉我,我真的应该在我的应用程序中使用 PDO 和准备好的语句。虽然我了解这些好处,但我很难理解我如何将它们实施到我的工作流程中。除了它使代码更清晰这一事实之外,我是否应该有一个特定的数据库类来容纳我所有准备好的语句,还是应该在每次我想运行查询时创建一个?我发现很难理解何时应该使用标准 PDO 查询以及何时应该使用准备好的语句。任何示例、提示或教程链接将不胜感激。
采纳答案by ólafur Waage
There are two great examples on the pdo::prepare()documentation.
pdo::prepare()文档中有两个很好的例子。
I have included them here and simplified them a bit.
我把它们包括在这里并稍微简化了它们。
This one uses ?parameters. $dbhis basically a PDO object. And what you are doing is putting the values 150and 'red'into the first and second question mark respectively.
这一个使用?参数。$dbh基本上是一个 PDO 对象。您正在做的是将值150和 分别'red'放入第一个和第二个问号。
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
This one uses named parameters and is a bit more complex.
这个使用命名参数,有点复杂。
/* 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();

