PDO mysql:如何知道插入是否成功

发布于 2024-08-09 21:45:36 字数 271 浏览 1 评论 0原文

我正在使用 PDO 插入一条记录(mysql 和 php)

$stmt->bindParam(':field1', $field1, PDO::PARAM_STR);
$stmt->bindParam(':field2', $field2, PDO::PARAM_STR);
$stmt->execute();

有没有办法知道它是否插入成功,例如记录是否因为重复而未插入?

编辑:我当然可以查看数据库,但我的意思是程序化反馈。

I'm using PDO to insert a record (mysql and 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.

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

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

发布评论

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

评论(7

心的憧憬 2024-08-16 21:45:36

PDOStatement->execute() returns true on success. There is also PDOStatement->errorCode() which you can check for errors.

帝王念 2024-08-16 21:45:36

鉴于最推荐的 PDO 错误模式是 ERRMODE_EXCEPTION直接 execute() 结果验证将无法工作。因为代码执行甚至无法达到其他答案中提供的条件。

因此,在 PDO 中处理查询执行结果有以下三种可能的情况:

  1. 判断是否成功,无需验证。只要保持你的程序流程就可以了。
  2. 要处理意外错误,请保持不变 - 不需要立即处理代码。如果出现数据库错误,则会引发异常,并且该异常将向上冒泡到站点范围的错误处理程序,最终导致常见的 500 错误页面。
  3. 要处理预期的错误(例如重复的主键),并且如果您有某种情况需要处理此特定错误,请使用 try..catch 运算符。

对于普通 PHP 用户来说,这听起来有点陌生 - 不验证操作的直接结果怎么样? - 但这正是异常的工作原理 - 您在其他地方检查错误。一次就完事了。极其方便。

所以,简而言之:在常规代码中,您根本不需要任何错误处理。只需保持你的代码不变:

$stmt->bindParam(':field1', $field1, PDO::PARAM_STR);
$stmt->bindParam(':field2', $field2, PDO::PARAM_STR);
$stmt->execute();
echo "Success!"; // whatever

成功时它会告诉你,出错时它会向你显示你的应用程序在这种情况下显示的常规错误页面。

仅当您有处理场景而不仅仅是报告错误时,请将插入语句放入 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!";

在上面的代码中,我们正在检查采取某些操作的特定错误,并为任何其他错误(例如没有这样的表)重新抛出异常,这将报告给程序员。

再次强调 - 只是告诉用户“您的插入成功”之类的内容不需要任何条件。

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.

So, there are three possible scenarios to handle the query execution result in PDO:

  1. To tell the success, no verification is needed. Just keep with your program flow.
  2. 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.
  3. 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..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 exactly how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.

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 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:

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.

静若繁花 2024-08-16 21:45:36

尝试查看 execute 的返回值,成功时为 TRUE,失败时为 FALSE

Try looking at the return value of execute, which is TRUE on success, and FALSE on failure.

少女的英雄梦 2024-08-16 21:45:36

如果更新查询使用与当前数据库记录匹配的值执行,则 $stmt->rowCount() 将返回 0,因为没有行受到影响。如果您有一个 if( rowCount() == 1 ) 来测试是否成功,您会认为更新失败,因为它没有失败,但值已经在数据库中,因此没有任何变化。

$stmt->execute();
if( $stmt ) return "success";

当我尝试使用违反的唯一键字段更新记录时,这对我不起作用。查询返回成功,但另一个查询返回旧字段值。

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->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.

泡沫很甜 2024-08-16 21:45:36

您可以测试行数

    $sqlStatement->execute( ...);
    if ($sqlStatement->rowCount() > 0)
    {
        return true;
    }

You can test the rowcount

    $sqlStatement->execute( ...);
    if ($sqlStatement->rowCount() > 0)
    {
        return true;
    }
身边 2024-08-16 21:45:36

PDOStatement->execute() 会抛出异常,

所以你能做的是

try
{
PDOStatement->execute();
//record inserted
}
catch(Exception $e)
{
//Some error occured. (i.e. violation of constraints)
}

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)
}
饭团 2024-08-16 21:45:36

使用 id 作为主键并自动递增

$stmt->execute();
$insertid = $conn->lastInsertId();

增量 id 始终大于零,即使在第一条记录上也是如此,这意味着它将始终返回 id 的真值,因为大于零在 PHP 中意味着 true

if ($insertid)
   echo "record inserted successfully";
else
   echo "record insertion failed";

Use id as primary key with auto increment

$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

if ($insertid)
   echo "record inserted successfully";
else
   echo "record insertion failed";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文