PHP/PDO:使用简单的准备好的语句与查询返回/受影响的行?

发布于 2024-09-18 13:48:58 字数 249 浏览 2 评论 0原文

我对 PDO 对象很陌生,找不到任何可以帮助我的文档。假设我有一个简单的代码来删除一行:

$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");

这将返回受影响的行,但是我将如何使用准备好的语句呢?可以使用 $dbh->prepare AND $dbh->exec 或查询!?

I am new to PDO objects and cannot find a single piece of documentation that will help me. Say I got a simple code to delete a row:

$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");

That will return affected rows, but how would I use prepared statements with that? Can use use $dbh->prepare AND $dbh->exec or query !?

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

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

发布评论

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

评论(2

涙—继续流 2024-09-25 13:48:58

它应该与任何其他语句相同:

$stmt = $dbh->prepare("DELETE FROM fruit WHERE colour = ?");
$stmt->execute(array('red'));
$count = $stmt->rowCount();

PDO 语句 rowCount() 应该是你想要做的。

编辑

通过添加->rowCount()来修复,这将返回行数。无论查询是否出错,语句中的 ->execute 都会返回 booltruefalse 。当然,所有这些信息都可以在 PDO 语句手册中轻松获得

It should be the same as any other statement:

$stmt = $dbh->prepare("DELETE FROM fruit WHERE colour = ?");
$stmt->execute(array('red'));
$count = $stmt->rowCount();

The PDO Statement rowCount() should be what you are looking to do.

EDIT

Fixed by adding the ->rowCount() which will return the row count. ->execute in a statement will return a bool, true or false whether the query errored out or not. Of course all of this information is readily available at the PDO Statement Manual

九命猫 2024-09-25 13:48:58

$dbh->prepare 返回一个 PDOStatement 对象。然后,您调用 $stmt->execute 来获取结果。

PDO 手册中的更多信息

以下是手册中的示例:

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$stmt = $dbh->prepare('SELECT name, colour, calories
                       FROM fruit
                       WHERE calories < ? AND colour = ?');
$stmt->execute(array($calories, $colour));
?>

$dbh->prepare returns a PDOStatement object. You then call $stmt->execute to get the result.

More info in the PDO manual

Here's an example from the manual:

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$stmt = $dbh->prepare('SELECT name, colour, calories
                       FROM fruit
                       WHERE calories < ? AND colour = ?');
$stmt->execute(array($calories, $colour));
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文