PHP PDO准备的语句 [英] PHP PDO prepared statements

查看:82
本文介绍了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准备的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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