php - 在 fat-free 框架中处理 'Duplicate-entry error'

标签 php mysql sql fat-free-framework

表中插入重复条目时如何处理错误? 我尝试了以下方法,但它不起作用。

function leaveBalanceRecord($f3)
{
    $sql = 
    "
    INSERT 
    INTO users_leave_balance (user_id, period, leave_type, leave_balance, rollable_till_date)
    VALUES (134, '2017-01', 1, 10.00, NULL)";
    $results = $this->db->exec($sql);
    if(!$results)
    {
        return 'Duplicate Entries';
    }
    return $results;
}

如果出现此错误,如何处理错误并更新记录? 任何帮助表示赞赏。谢谢。

最佳答案

针对您的情况,我看到了两种解决方案:

1) 利用 MySQL REPLACE INTO 语法:

$sql='REPLACE INTO users_leave_balance etc.';
$this->db->exec($sql);

来自docs :

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

2)捕获PDO异常:

$sql='INSERT INTO users_leave_balance etc.';
try {
  $this->db->exec($sql);
} catch (\PDOException $e) {
  $err=$e->errorInfo;
  if ($err[0]==23000) {
    // duplicate key: do something
  } else {
    // any other error
  }
}

参见 this answer有关如何启用 PDO 异常的详细信息。

关于php - 在 fat-free 框架中处理 'Duplicate-entry error',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47391474/

相关文章:

php - 如何使用查询将动态表单数据从 javascript 保存到数据库

mysql - Sql 触发器条件检查不起作用

php - 如何让我的 cron 工作在 cpanel 中工作?

php - 多维数组与多数组

sql - 数据库设计 - 具有属性的多类别产品

mysql - 发送 SQL 查询并读取文本文件

PHP 扩展 - 使用 PHP 发布编译的段错误

php - 用于 PHP 托管的 PowerPC Linux 计算机总是抛出 "Balloc() allocation exceeds list boundary"错误