【问题标题】:Catch Duplicate entry with prepared SQL statement使用准备好的 SQL 语句捕获重复条目
【发布时间】:2015-10-06 21:19:20
【问题描述】:

我想用准备好的 MySQL 语句处理“重复条目”错误。

我有那些台词

$result = $db->prepare("INSERT INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
$result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date));

如果没有任何错误,想要执行一些代码。并显示一个弹出窗口并在出现错误时使 prog 死亡。

我已经试过了

if($result === false)//Catch error
{}
else //It worked
{}

但是没有用

【问题讨论】:

  • 您正在检查 PDO 语句本身。您应该检查返回值。但更好的是使用errorCodeerrorInfo

标签: php mysql error-handling


【解决方案1】:

您可以使用INSERT IGNORE,然后使用PDOStatement::rowCount检查受影响的行数

概念应该是这样的:

$result = $db->prepare("INSERT IGNORE INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
if ($result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date))) {
  if ($result->rowCount() == 0) {
   // You had a duplicate record.
  } else {
   // all good.
  }
}

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    相关资源
    最近更新 更多