I have a table with user information. One column has the roles assigned for the user in the form of a checkbox. Now, I want the table containing those records to be updated when the checkbox is unchecked. For example, user1 is Admin > Admin checkbox is checked; I unchecked the checkbox > Record from table gets deleted. I want to use PHP only. I found this example, but I cannot get it to work:
if (isset($_POST['formWasSubmitted'])) {
//form was submitted...let's DO this.
if (!isset($_POST['checkboxname'])) {
// checkbox was not checked...do something
} else {
// checkbox was checked. Rock on!
}
}
Checkbox gets created:
for ($a = 1; $a <= $count ; $a++){
$new_sql = "SELECT role_id from users_roles, users WHERE users_roles.user_id = '".$row["user_id"]."' AND users_roles.role_id = '" . $a . "' GROUP BY users_roles.user_id";
$checked_or_not = mysqli_query($connect, $new_sql);
if ($checked_or_not->num_rows != 0){
echo "<input type='checkbox' checked name='techno[]' value='$a' />" .$roles[($a-1)]. "<br>";
}
else if ($checked_or_not->num_rows == 0){
echo "<input type='checkbox' name='techno[]' value='$a' />" .$roles[($a-1)]. "<br>";
}
}
Wait for submit button to be pressed and INSERT/DELETE record:
<?PHP
$records_roles = mysqli_query($connect, "SELECT * FROM roles");
$roles = array();
$count = 0;
while ($course_roles = mysqli_fetch_assoc($records_roles)){
$roles [] =
$course_roles['role_name'];
$count++;
}
if(isset($_POST['checkSubmit'])){ // Use button name
$user_id = $_POST['user_id'];
$checkbox1=$_POST['techno'];
if (!$checkbox1) {
// checkbox was not checked...do something
for ($i=0; $i<$count;$i++) {
$query2 = "DELETE FROM users_roles WHERE user_id = '$user_id' AND role_id = '" . $checkbox1[$i] . "' "; // role_id is empty
// _log($query2); = DELETE FROM users_roles WHERE user_id = '2' AND role_id = ''
$in_ch2 = mysqli_query($connect, $query2);
}
} else {
// checkbox was checked. Rock on!
for ($i=0; $i<sizeof ($checkbox1);$i++) {
$query="INSERT INTO users_roles(user_id, role_id) VALUES ('$user_id', '".$checkbox1[$i]."')";
//_log('Insert new role to user: ' . $query);
$in_ch=mysqli_query($connect, $query);
}
}
if($in_ch==1)
{
echo'<script>alert("Inserted Successfully")</script>';
}
else
{
echo'<script>alert("Failed to Insert")</script>';
}
echo "<meta http-equiv='refresh' content='0'>";
$connect->close();
}
?>
Aucun commentaire:
Enregistrer un commentaire