问题描述
我有 3 个 session_id
数组。我试图一一检查它们是否已经存在于数据库中。然后跳过已经存在的并将其他 session_id
添加到数据库中。
PHP 脚本:
foreach($json['sessions'] as $data)
{
//Check if the same session is already exists in database
$prep_stmt = "SELECT id FROM sessions WHERE session_id = ? LIMIT 1";
$stmt = $MysqLi->prepare($prep_stmt);
$stmt->bind_param('s',$data['session_id']);
$stmt->execute();
$stmt->store_result();
//If the session is not already exist,add it
if (!$stmt->num_rows == 1) {
$stmt->close();
$a_stmt = $MysqLi->prepare("INSERT INTO sessions (session_id) VALUES (?)");
$a_stmt->bind_param('s',$data['session_id']);
$rc = $a_stmt->execute();
}
else {
exit ('Already exists')
}
}
如果三个 session_id
都不存在,它会将所有三个 session_id
添加到数据库中。如果这三个都存在,它会跳过所有这些。但问题是,如果它发现其中一两个已经存在于数据库中,它也会跳过所有其他 <LinearLayout
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/gray_skeleton"
android:orientation="vertical">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragmentGrafic"
android:name="Fragment1" />
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragmentGrafic"
android:name="Fragment2" />
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragmentGrafic"
android:name="Fragment3" />
...
</LinearLayout>
。
解决方法
你处理这个问题的方式是错误的。如果 session_id
应该是唯一的,请告诉数据库,并让它处理冲突。
为此,请向表中添加唯一索引:
ALTER TABLE `StackOverflow`.`sessions`
ADD UNIQUE INDEX `session_id_UNIQUE2` (`session_id`);
现在你不需要在插入前检查表格,所以修改你的代码:
// IGNORE throws a warning instead of an error. We can handle this later
$a_stmt = $mysqli->prepare("INSERT IGNORE INTO sessions (session_id) VALUES (?)");
// store any duplicate session IDs,if required
$duplicateSessions = [];
foreach($json['sessions'] as $data)
{
$a_stmt->bind_param('s',$data['session_id']);
$rc = $a_stmt->execute();
if ($rc === false) {
throw new Exception($mysqli->error);
}
// Check if the session was inserted. If not,store the ID
if ($mysqli->affected_rows === 0) {
$duplicateSessions[] = $data['session_id'];
}
}
// Handle the duplicates here
$dups = "Duplicates sessions: ".implode(",",$duplicateSessions);
exit($dups);