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.
编辑:我当然可以查看数据库,但我指的是程序化的反馈。
7 个解决方案
#1
103
PDOStatement->execute()
returns true on success. There is also PDOStatement->errorCode()
which you can check for errors.
执行()成功时返回true。还有PDOStatement->errorCode(),您可以在其中检查错误。
#2
15
Wonder why there is still no proper answer.
不知道为什么仍然没有合适的答案。
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,因此直接执行()结果验证永远无法工作。因为代码执行甚至不能达到其他答案所提供的条件。
So, there are three possible scenarios for handling the result of insert operation in PDO:
因此,处理PDO中插入操作的结果有三种可能的情况:
- To tell the success, no verification is needed. Just keep with your program flow.
- 要讲成功,就不需要验证。只要遵守你的程序流程。
- To handle an 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.
- 要处理意外错误,请保持不变——不需要立即处理代码。在发生数据库错误时,将抛出一个异常,该异常将出现在站点范围内的错误处理程序中,最终将导致一个常见的500错误页面。
- To handle an expected error, like a duplicate primary key, and if you have a certain scenario to handle this very error - then use a
try..catch
operator. - 要处理预期的错误,比如重复的主键,如果您有一个特定的场景来处理这个错误,那么请尝试…操作符。
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 how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.
对于一个普通的PHP用户来说,这听起来有点陌生——为什么不验证操作的直接结果呢?-但这就是异常的工作原理-您可以在其他地方检查错误。一次。极其方便。
So, in a regular case you don't need any handling code 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 scenario other than just reporting the error, put your insert statement in a try..catch
operator, check whether it was the error you expected and handle it; or - if the error was any different - re-throw the 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:
只有当你有一个处理场景而不是仅仅报告错误时,才可以尝试插入语句。捕获操作符,检查它是否是您期望的错误并处理它;或者——如果错误有任何不同——重新抛出异常,以使站点范围内的错误处理程序能够以通常的方式处理它。下面是我关于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.
再说一遍——仅仅是告诉用户“您的插入成功了”之类的话,根本不需要任何条件。
#3
9
Try looking at the return value of execute
, which is TRUE
on success, and FALSE
on failure.
尝试查看执行的返回值,这在成功时为真,在失败时为假。
#4
8
If an update query executes with values that match the current database record then $stmt->rowCount()
will return 0
for 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.
当我试图用被侵犯的唯一键字段更新一条记录时,这对我不起作用。查询返回成功,但另一个查询返回旧字段值。
#5
1
You can test the rowcount
您可以测试行数
$sqlStatement->execute( ...);
if ($sqlStatement->rowCount() > 0)
{
return true;
}
#6
0
PDOStatement->execute() can throw an exception
执行()可以抛出异常
so what you can do is
你能做的是
try
{
PDOStatement->execute();
//record inserted
}
catch(Exception $e)
{
//Some error occured. (i.e. violation of constraints)
}
#7
0
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总是大于零,即使是在第一个记录中,这意味着它总是返回一个真正的值,在PHP中,大于0的id是正确的。
if ($insertid)
echo "record inserted successfully";
else
echo "record insertion failed";
#1
103
PDOStatement->execute()
returns true on success. There is also PDOStatement->errorCode()
which you can check for errors.
执行()成功时返回true。还有PDOStatement->errorCode(),您可以在其中检查错误。
#2
15
Wonder why there is still no proper answer.
不知道为什么仍然没有合适的答案。
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,因此直接执行()结果验证永远无法工作。因为代码执行甚至不能达到其他答案所提供的条件。
So, there are three possible scenarios for handling the result of insert operation in PDO:
因此,处理PDO中插入操作的结果有三种可能的情况:
- To tell the success, no verification is needed. Just keep with your program flow.
- 要讲成功,就不需要验证。只要遵守你的程序流程。
- To handle an 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.
- 要处理意外错误,请保持不变——不需要立即处理代码。在发生数据库错误时,将抛出一个异常,该异常将出现在站点范围内的错误处理程序中,最终将导致一个常见的500错误页面。
- To handle an expected error, like a duplicate primary key, and if you have a certain scenario to handle this very error - then use a
try..catch
operator. - 要处理预期的错误,比如重复的主键,如果您有一个特定的场景来处理这个错误,那么请尝试…操作符。
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 how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.
对于一个普通的PHP用户来说,这听起来有点陌生——为什么不验证操作的直接结果呢?-但这就是异常的工作原理-您可以在其他地方检查错误。一次。极其方便。
So, in a regular case you don't need any handling code 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 scenario other than just reporting the error, put your insert statement in a try..catch
operator, check whether it was the error you expected and handle it; or - if the error was any different - re-throw the 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:
只有当你有一个处理场景而不是仅仅报告错误时,才可以尝试插入语句。捕获操作符,检查它是否是您期望的错误并处理它;或者——如果错误有任何不同——重新抛出异常,以使站点范围内的错误处理程序能够以通常的方式处理它。下面是我关于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.
再说一遍——仅仅是告诉用户“您的插入成功了”之类的话,根本不需要任何条件。
#3
9
Try looking at the return value of execute
, which is TRUE
on success, and FALSE
on failure.
尝试查看执行的返回值,这在成功时为真,在失败时为假。
#4
8
If an update query executes with values that match the current database record then $stmt->rowCount()
will return 0
for 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.
当我试图用被侵犯的唯一键字段更新一条记录时,这对我不起作用。查询返回成功,但另一个查询返回旧字段值。
#5
1
You can test the rowcount
您可以测试行数
$sqlStatement->execute( ...);
if ($sqlStatement->rowCount() > 0)
{
return true;
}
#6
0
PDOStatement->execute() can throw an exception
执行()可以抛出异常
so what you can do is
你能做的是
try
{
PDOStatement->execute();
//record inserted
}
catch(Exception $e)
{
//Some error occured. (i.e. violation of constraints)
}
#7
0
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总是大于零,即使是在第一个记录中,这意味着它总是返回一个真正的值,在PHP中,大于0的id是正确的。
if ($insertid)
echo "record inserted successfully";
else
echo "record insertion failed";