gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:43:06 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com