PHP PDO prepared statements(PHP PDO 准备好的语句)
问题描述
今天有人告诉我,我真的应该在我的应用程序中使用 PDO 和准备好的语句.虽然我了解这些好处,但我很难理解如何将它们实施到我的工作流程中.除了它使代码更干净这一事实之外,我应该有一个特定的数据库类来容纳我所有准备好的语句,还是应该在每次我想运行查询时创建一个?我发现很难理解什么时候应该使用标准 PDO 查询以及什么时候应该使用准备好的语句.任何示例、提示或教程链接将不胜感激.
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::prepare() 文档.
我已将它们包含在此处并进行了一些简化.
I have included them here and simplified them a bit.
这个使用 ?
参数.$dbh
基本上是一个 PDO 对象.而您正在做的是将值 150
和 'red'
分别放入第一个和第二个问号.
This one uses ?
parameters. $dbh
is basically a PDO object. And what you are doing is putting the values 150
and 'red'
into the first and second question mark respectively.
/* 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();
这篇关于PHP PDO 准备好的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP PDO 准备好的语句


基础教程推荐
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在多维数组中查找最大值 2021-01-01