PHP/PDO: use simple prepared statement with query return/affected rows?

你离开我真会死。 提交于 2019-12-07 09:40:09

问题


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 !?


回答1:


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




回答2:


$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));
?>


来源:https://stackoverflow.com/questions/3659898/php-pdo-use-simple-prepared-statement-with-query-return-affected-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!