如何判断查询何时在 PHP PDO 中成功执行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9521228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to tell when query executed successfully in PHP PDO?
提问by Chuck Le Butt
How can I test to see if the following query executed successfully?
如何测试以下查询是否成功执行?
$STH = $this->_db->prepare("UPDATE UserCreds SET
VerificationString=:newVerificationString, ExpiryDate=:expiryDate
WHERE UserID = :userID;");
$STH->execute($params);
I know I can use lastInsertId()
when I'm adding new rows, but what about UPDATEs and SELECTs?
我知道我可以lastInsertId()
在添加新行时使用,但是 UPDATE 和 SELECT 呢?
回答by Sarfraz
The execute
returns true
on success and false
on failure.
成功和失败的execute
回报。true
false
Returns TRUE on success or FALSE on failure.
成功时返回 TRUE,失败时返回 FALSE。
So you can make sure query ran successfully like:
因此,您可以确保查询成功运行,例如:
if ($STH->execute($params))
{
// success
}
else
{
// failure
}
回答by Marc B
execute() returns true/false based on success/failure of the query:
execute() 根据查询的成功/失败返回真/假:
$status = $STH->execute($params);
if ($status) {
echo 'It worked!';
} else {
echo 'It failed!';
}
One note: a select query which returns no rows is NOT a failure. It's a perfectly valid result that just happens to have NO results.
一个注意事项:不返回任何行的选择查询不是失败。这是一个完全有效的结果,只是碰巧没有结果。
回答by Bashir Noori
simply i can count the number of row effected:
只是我可以计算受影响的行数:
$stmt->execute();
$count = $stmt->rowCount();
if($count =='0'){
echo "Failed !";
}
else{
echo "Success !";
}
回答by Nikhil Thombare
This is best way to verify Doctrine query result return success or failed result and same way as per above suggest to check weather query returns Success on Trueand Failed on false.
这是验证 Doctrine 查询结果返回成功或失败结果的最佳方法,与上述相同的方法建议检查天气查询返回Success on True和Failed on false。
public static function removeStudent($teacher_id){
$q = Doctrine_Query::create()
->delete('Student s')
->where('s.teacher_id = ?');
$result = $q->execute(array($teacher_id));
if($result)
{
echo "success";
}else{
echo "failed";
}
}