当INSERT INTO包含foreach循环时,有关如何为完整性约束违规创建自定义错误消息的任何想法?
$states is an array;
$franchise_id is an integer;
查询:
public static function update($franchise_id, $states)
{
try
{
// establish db connection
$db = static::getDB();
$sql = "INSERT INTO franchise_states SET
state_id = :state_id,
franchise_id = :franchise_id";
$stmt = $db->prepare($sql);
foreach($states as $state)
{
$stmt->execute([':state_id' => $state, ':franchise_id' => $franchise_id]);
}
return $stmt;
}
catch (PDOException $e)
{
echo "Error updating franchise data: " . $e->getMessage();
exit();
}
}
我想添加这样的内容 -
echo '<script>';
echo 'alert("State already included.")';
echo '</script>';
- 所以用户可以留在同一页面上。
catch块中的解决方案如下:
if ($e->errorInfo[1] == 23000) {
....
}
无效。也许是因为在循环第一次迭代之后抛出了错误。
这两个都不是:
foreach($states as $state)
{
$result = $stmt->execute([':state_id' => $state, ':franchise_id' => $franchise_id]);
if (!result)
{
...
}
}
当循环运行第一次迭代时,它似乎遇到约束违规,因此之后的代码不会被执行。不确定那是否真的发生了什么。
似乎必须插入自定义错误消息。如果有人知道如何,我将不胜感激任何想法或建议。
错误:
Fatal error
Uncaught exception: 'PDOException'
Message: 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '5-1' for key 'franchise_state_id''
Stack trace:
#0 C:\xampp\htdocs\agt\App\Models\Franchise_state.php(69): PDOStatement->execute(Array)
#1 C:\xampp\htdocs\agt\App\Controllers\Admin\Franchisors.php(336): App\Models\Franchise_state::update('5', Array)
#2 C:\xampp\htdocs\agt\Core\Router.php(206): App\Controllers\Admin\Franchisors->update()
#3 C:\xampp\htdocs\agt\public\index.php(162): Core\Router->dispatch('admin/franchiso...')
#4 {main}
答案 0 :(得分:1)
Integrity constraint violation: 1062 Duplicate entry '5-1' for key 'franchise_state_id''
Indicates unique key violation, and franchise_state_id
column doesn't allow duplicate values. If duplicate value is expected in franchise_state_id
, then you need to alter you table to remove unique constraint from franchise_state_id
column.
But, if it expected to store unique value, then you need to make changes to application to make sure, you don't pass duplicate entry (validate if entry already exists from database).