在 fat-free 框架中处理 'Duplicate-entry error'
Handle 'Duplicate-entry error' in fat-free framework
在table中插入重复条目时如何处理错误?
我尝试了以下但它不起作用。
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;
}
如果出现此错误,如何处理错误并更新记录?
任何帮助表示赞赏。谢谢
看起来你应该只添加另一个执行 sql,更新,而不是在你的 return 部分评论
针对您的情况,我看到了两种解决方案:
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
}
}
有关如何启用 PDO 异常的详细信息,请参阅 。
在table中插入重复条目时如何处理错误? 我尝试了以下但它不起作用。
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;
}
如果出现此错误,如何处理错误并更新记录? 任何帮助表示赞赏。谢谢
看起来你应该只添加另一个执行 sql,更新,而不是在你的 return 部分评论
针对您的情况,我看到了两种解决方案:
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
}
}
有关如何启用 PDO 异常的详细信息,请参阅