PHP PDO 准备好的语句

发布于 2024-08-04 22:43:14 字数 199 浏览 0 评论 0原文

今天有人告诉我,我真的应该在我的应用程序中使用 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十雾 2024-08-11 22:43:14

pdo::prepare() 文档中有两个很好的示例。

我已将它们包含在这里并进行了一些简化。

这个使用 ? 参数。 $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();

这个使用命名参数并且有点复杂。

/* 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);
$sth->execute(array(':calories' => 150, ':colour' => 'red'));

$red = $sth->fetchAll();

There are two great examples on the pdo::prepare() documentation.

I have included them here and simplified them a bit.

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);
$sth->execute(array(':calories' => 150, ':colour' => 'red'));

$red = $sth->fetchAll();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文