使用我的代码,如果用户选中其中一个名称旁边的复选框 当用户单击“保存”时,名称将保存到我的 review_shared 表中。
但我只想保存选中的值 一旦进入表格,它就会按照现在的方式保存多次 - 我的意思是,如果用户返回此页面并检查名称,然后用户再次单击“保存”。
我可以在代码中添加什么来实现这一点,这样它只会在我的 review_shared 表中保存一次?目前它看起来像这样,它保存了多次:
if(!empty($_POST['check_contacts'])) {
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
//go to the main page when changes have been saved
header('Location:volleyLogin.php');
}
$con->close();
我认为在上面添加这样的代码会有帮助,但事实并非如此:
if(!empty($_POST['check_contacts'])) {
//************************* added this in **************
$check="";
//if the contact in review_shared is already checked, we don't want to save it multiple times
$already_checked = "SELECT * from review_shared WHERE user_id = '$user_id' AND contact_id = '$check' AND review_id = " .$_GET['id'];
$already_checked_result=mysqli_query($con,$already_checked);
$num_rows = mysqli_num_rows($already_checked_result);
if($num_rows >= 1) {
echo "This is already a contact";
break;
}
//*******************************************************
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
//go to the main page when changes have been saved
header('Location:volleyLogin.php');
}
$con->close();
最佳答案
break;
用于退出循环(for
、foreach
、while
和 do-while
)和 switch
结构,而不是来自 if
block 。您必须创建一个与 that if
block 相对应的 else
block ,并将整个 foreach
循环放在那里。
// your code
if($num_rows) {
echo "This is already a contact";
}else{
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
}
// your code
相关引用资料如下:
关于php - 如何确保在检查时该值仅保存到表中一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42595020/