php PDO mysql:如何知道插入是否成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1661863/
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
PDO mysql: How to know if insert was successful
提问by Chris
I'm using PDO to insert a record (mysql and php)
我正在使用 PDO 插入记录(mysql 和 php)
$stmt->bindParam(':field1', $field1, PDO::PARAM_STR);
$stmt->bindParam(':field2', $field2, PDO::PARAM_STR);
$stmt->execute();
Is there a way to know if it inserted successfully, for example if the record was not inserted because it was a duplicate?
有没有办法知道它是否插入成功,例如记录是否因为重复而没有插入?
Edit: of course I can look at the database, but I mean programmatic feedback.
编辑:当然我可以查看数据库,但我的意思是程序化反馈。
回答by ólafur Waage
PDOStatement->execute()returns true on success. There is also PDOStatement->errorCode()which you can check for errors.
PDOStatement->execute()成功时返回真。还有PDOStatement->errorCode(),你可以检查错误。
回答by Your Common Sense
Given that most recommended error mode for PDO is ERRMODE_EXCEPTION, no direct execute()result verification will ever work. As the code execution won't even reach the condition offered in other answers.
鉴于最推荐的 PDO 错误模式是ERRMODE_EXCEPTION,没有任何直接的execute()结果验证会起作用。由于代码执行甚至不会达到其他答案中提供的条件。
So, there are three possible scenarios to handle the query execution result in PDO:
因此,在 PDO 中处理查询执行结果有三种可能的场景:
- To tell the success, no verification is needed. Just keep with your program flow.
- To handle the unexpected error, keep with the same - no immediate handling code is needed. An exception will be thrown in case of a database error, and it will bubble up to the site-wide error handler that eventually will result in a common 500 error page.
- To handle the expected error, like a duplicate primary key, and if you have a certain scenario to handle this particular error, then use a
try..catchoperator.
- 要说成功,不需要验证。只要保持你的程序流程。
- 要处理意外错误,请保持不变 - 不需要立即处理代码。如果发生数据库错误,将抛出异常,并将冒泡到站点范围的错误处理程序,最终将导致常见的 500 错误页面。
- 要处理预期的错误,例如重复的主键,并且如果您有特定场景来处理此特定错误,请使用
try..catch运算符。
For a regular PHP user it sounds a bit alien - how's that, not to verify the direct result of the operation? - but this is exactly how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.
对于普通的 PHP 用户来说,这听起来有点陌生 - 怎么办,不验证操作的直接结果?- 但这正是异常的工作方式 - 您可以在其他地方检查错误。一次就好。非常方便。
So, in a nutshell: in a regular code you don't need any error handling at all. Just keep your code as is:
因此,简而言之:在常规代码中,您根本不需要任何错误处理。只需保持您的代码不变:
$stmt->bindParam(':field1', $field1, PDO::PARAM_STR);
$stmt->bindParam(':field2', $field2, PDO::PARAM_STR);
$stmt->execute();
echo "Success!"; // whatever
On success it will tell you so, on error it will show you the regular error page that your application is showing for such an occasion.
成功时它会告诉你,出错时它会显示你的应用程序在这种情况下显示的常规错误页面。
Only in case you have a handling scenarioother than just reporting the error, put your insert statement in a try..catchoperator, check whether it was the error you expected and handle it; or - if the error was any different - re-throwthe exception, to make it possible to be handled by the site-wide error handler usual way. Below is the example code from my article on error handling with PDO:
只有当你有一个处理场景而不只是报告错误时,把你的插入语句放在一个try..catch操作符中,检查它是否是你期望的错误并处理它;或者 - 如果错误有任何不同 -重新抛出异常,以便可以通过站点范围的错误处理程序通常的方式进行处理。下面是我关于使用 PDO 处理错误的文章中的示例代码:
try {
$pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
if ($e->getCode() == 1062) {
// Take some action if there is a key constraint violation, i.e. duplicate name
} else {
throw $e;
}
}
echo "Success!";
In the code above we are checking for the particular error to take some action and re-throwing the exception for the any other error (no such table for example) which will be reported to a programmer.
在上面的代码中,我们正在检查特定错误以采取一些行动,并为将报告给程序员的任何其他错误(例如没有这样的表)重新抛出异常。
While again - just to tell a user something like "Your insert was successful" no condition is ever needed.
再次 - 只是告诉用户诸如“您的插入成功”之类的内容,不需要任何条件。
回答by Dominic Rodger
回答by dan
If an update query executes with values that match the current database record then $stmt->rowCount()will return 0for no rows were affected. If you have an if( rowCount() == 1 )to test for success you will think the updated failed when it did not fail but the values were already in the database so nothing change.
如果更新查询使用与当前数据库记录匹配的值执行,$stmt->rowCount()则将返回0没有受影响的行。如果您if( rowCount() == 1 )要测试成功,您会认为更新失败了,因为它没有失败,但值已经在数据库中,所以没有任何变化。
$stmt->execute();
if( $stmt ) return "success";
This did not work for me when I tried to update a record with a unique key field that was violated. The query returned success but another query returns the old field value.
当我尝试使用违反的唯一键字段更新记录时,这对我不起作用。查询返回成功,但另一个查询返回旧字段值。
回答by crafter
You can test the rowcount
您可以测试行数
$sqlStatement->execute( ...);
if ($sqlStatement->rowCount() > 0)
{
return true;
}
回答by jumper rbk
Use id as primary key with auto increment
使用 id 作为主键并自动递增
$stmt->execute();
$insertid = $conn->lastInsertId();
incremental id is always bigger than zero even on first record so that means it will always return a true value for id coz bigger than zero means true in PHP
增量 id 总是大于零,即使在第一条记录上,这意味着它总是会为 id 返回一个真值,因为大于零意味着在 PHP 中为真
if ($insertid)
echo "record inserted successfully";
else
echo "record insertion failed";
回答by Sumit P Makwana
PDOStatement->execute() can throw an exception
PDOStatement->execute() 可以抛出异常
so what you can do is
所以你可以做的是
try
{
PDOStatement->execute();
//record inserted
}
catch(Exception $e)
{
//Some error occured. (i.e. violation of constraints)
}

