使用我的代码,如果用户选中其中一个名称旁边的复选框 当用户点击“保存”时,名称会保存到我的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();
答案 0 :(得分:1)
break;
用于循环(for
,foreach
,while
和do-while
)和switch
结构,而不是来自if
区块。您必须创建与 else
块对应的if
块,并将整个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
以下是相关参考: