I have an html table with bootstrap-multiselect in one of the columns. I want the database to delete the role when the checkbox is unchecked.
I am listening to the changes using if (isset($_POST['roles_checkbox'])). Therefore, when the checkbox is unchecked, it never gets called and nothing happens. If the user has 2 roles and 1 gets unchecked it gets deleted. Nevertheless, if the user has 1 role it cannot be deleted. I want the users to be able to have no role assigned to them.
<?php
echo "
<!--User Roles-->
<td>
<form method='post'>
<input type='hidden' name='user_id' value=" . $row["user_id"] . ">"; ?>
<select class='roles_checkbox' multiple='multiple' name="roles_checkbox[]"
onchange='this.form.submit()'>
<?php $a = 1; ?>
<?php foreach ($roles as $data):
$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);?>
<option value="<?php echo $a ?>" <?php if ($checked_or_not->num_rows != 0) echo
"selected=\"selected\""; ?>><?php echo $data ?></option>
<?php $a++; ?>
<?php endforeach; ?>
</select>
<?php
echo "
</form>
</td>";
<!--Update User Role listenning to select box-->
if (isset($_POST['roles_checkbox'])) { // Use select name
$user_id = $_POST['user_id']; // Use input name to get user id being modify
// Start by deleting all the roles
for ($i = 0; $i < $count; $i++) {
$a = $i + 1;
// Deleted all roles
$query2 = "DELETE FROM users_roles WHERE user_id = '$user_id' AND role_id = '$a'";
_log('$query2: ' . $query2);
$in_ch2 = mysqli_query($connect, $query2);
}
foreach ($_POST['roles_checkbox'] as $selectedOption) {
//echo $selectedOption . "\n";
// Insert selected roles
$query = "INSERT INTO users_roles(user_id, role_id) VALUES ('$user_id', '" . $selectedOption . "')";
$in_ch = mysqli_query($connect, $query);
}
echo "<meta http-equiv='refresh' content='0'>";
$connect->close();
}
?>
I think you're on the right path with your attempt at deleting all current user roles before reinserting the new ones. However, I think this is also where the issue lies.
Try instead of this:
// Start by deleting all the roles
for ($i = 0; $i < $count; $i++) {
$a = $i + 1;
// Deleted all roles
$query2 = "DELETE FROM users_roles WHERE user_id = '$user_id' AND role_id = '$a'";
_log('$query2: ' . $query2);
$in_ch2 = mysqli_query($connect, $query2);
}
Doing this:
$delete_query = "DELETE FROM users_roles WHERE user_id = '$user_id'";
mysqli_query($connect, $delete_query);
EDIT based on comments
Knowing that user can have no roles, you would start be removing your initial input check if ($_POST['roles_checkbox']) and reqlacing it for a user id check i.e. if ($_POST['user_id']) this allows you to continue running the rest of your process without relying on roles input. See my updated example below...
// First check if the request includes a user id
$user_id = !empty($_POST['user_id']) ? (int)$_POST['user_id'] : null;
if ($user_id) {
// Second, lets delete all existing roles
$delete_query = "DELETE FROM users_roles WHERE user_id = '$user_id'";
mysqli_query($connect, $delete_query);
// Now we check if the request includes any selected role
if (!empty($_POST['roles_checkbox'])) {
// This array will hold MySQL insert values
$insert_values = [];
// Loop through request values, sanitizing and validating before add to our query
foreach ($_POST['roles_checkbox'] as $role_id) {
if ($role_id = (int)$role_id) {
$insert_values[] = "('{$user_id}', '{$role_id}')";
}
}
// Double check we have insert values before running query
if (!empty($insert_values)) {
$insert = "INSERT INTO users_roles(user_id, role_id) VALUES " . implode( ', ', $insert_values );
mysqli_query($connect, $insert);
}
}
echo '<meta http-equiv="refresh" content="0">';
$connect->close();
}
Related
EDIT: Here is the SQL SELECT
$statement = $db->prepare("
SELECT A.Vorname
, A.Nachname
, O.IndexcardRight
, O.QuizRight
, O.Admin_AdminID
FROM Admin A
LEFT
JOIN AdminOfModule O
ON O.Admin_AdminID = A.AdminID
WHERE O.AdminTyp = 'Student'
GROUP
BY A.AdminID
");
$statement->execute();
$admin = $statement->fetchAll(PDO::FETCH_ASSOC);
$count = $statement->rowCount();
Here is the PHP and HTML Code with the Update SQL
which doenst work for sure because i have no unique id's
i tried some stuff like give in the name or id quiz[] but i cannot call it in the php function. And couldnt find much ways to do it.
<form method="post">
<?php
$i = 2;
$y = 2;
foreach ($admin as $row) {
$aii = $row['Admin_AdminID'];
$i++;
$y++;
echo '<label>' . $row["Vorname"] . $row["Nachname"] . '</label>';
echo '<br>';
echo '<label> Quiz</label>';
//echo'<input type="hidden>"';
echo '<input type="checkbox" name="quiz' . $i . '" id="quiz' . $i . '"> ';
echo '';
echo '<label> Indexcard</label>';
echo '<input type="checkbox" name="indexcard' . $i . '" id="indexcard' . $i . '">';
echo '<br>';
//quizx indexcardx wenn button geklickt und wenn quizx isset dann update table adminofmodule set quizright =1 where
}
if (isset($_POST['submit'])) {
//$ic = $_POST["indexcard$i"];
//$q = $_POST["quiz$i"];
if (isset($_POST["quiz$i"])) {
$stmt = $db->prepare("UPDATE AdminOfModule SET QuizRight = 1 WHERE '$aii' = '$i' ");
$stmt->execute();
}
else {
$stmt1 = $db->prepare("UPDATE AdminOfModule SET QuizRight = 0 WHERE '$aii' = '$i' ");
$stmt1->execute();
}
if (isset($_POST["indexcard$i"])) {
$stmt2 = $db->prepare("UPDATE AdminOfModule SET IndexcardRight = 1 WHERE'$aii' = '$i'");
$stmt2->execute();
}
else {
$stmt3 = $db->prepare("UPDATE AdminOfModule SET IndexcardRight = 0 WHERE'$aii' = '$i' ");
$stmt3->execute();
}
}
echo '<input type="submit" name="submit" id="submit">';
?>
</form>
The Problem is, if i check the Checkbox at the first rows it will stand 0 but if click the last Checkbox it sets all to 1.
In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.
You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here
It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">
My dropdown menu is loading from the database, I can select multiple options from the list. When I click my 'Add' button everything appears to be behaving as expected, apart from the fact that nothing is saving back to the database. Unfortunately I've done so many tweaks now, having looked at stack overflow and others, I'm in the realm of confusion rather than progress.
I have set up a logger file to show when a page is reached. So I can confirm that I do get to the insert_rooms.inc.php page.
<?php
session_start(); // gets current session data for user // this function sends headers so it cannot be called after any output.
require_once '../dbconfig.php';
$date = new DateTime();
$date = $date->format("y:m:d h:i:s");
$id = $_SESSION['u_nickname'];
$u_id = $_SESSION['u_id'];
$file = "../ips.txt";
$text = file_get_contents($file);
$text .= $date ." " . $id . " visited insert_rooms.inc.php"."\n"; ///////// this text must be changed for each page
file_put_contents($file, $text);
$conn = OpenCon();
if ($conn)
{
if(isset($_POST['room[]']))
{
$room = mysqli_real_escape_string($conn, $_POST['room']);
if($room) // if a room exists insert into db with users id.
{
foreach($_POST['room'] as $r)
{
//here we need to take for example the word kitchen and find the id belonging to kitchen from the master_rooms table use it to find the master_room_id for kitchen and insert that into the table called user_room_list - along with the user id taken from the session u_id
$room_id = mysqli_query($conn, "SELECT master_room_id FROM master_rooms WHERE master_room_name = '$r'");
$sql = "INSERT INTO user_room_list(user_info_id, master_room_id)
VALUES(' ".$u_id." ', ' " .$room_id. " ') ";
mysqli_query($conn, $sql);
}
}
}
//session_unset();
//session_destroy();
header("Location: ../room_choice.php");
exit();
CloseCon($conn);
}
?>
extract from other file:
<div class="dropdown">
<form action="includes/insert_rooms.inc.php" method="POST">
"Hold down the Ctrl (windows) / Command (Mac) button to select multiple options."
<br/>
<br/>
<select name="room[]" multiple>
<?php
$conn = OpenCon();
if ($conn)
{
$query = "SELECT master_room_name FROM master_rooms";
mysqli_query($conn, $query) or die('Error querying database.');
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
for ($i = 0; $i < count($row); $i++)
{
echo "<option value=". $row[$i] . ">" . $row[$i] ."</option>";
}
}
CloseCon($conn);
echo "</select>";
echo " <input type="."submit"." value="." Add "." name="."send"."> ";
echo " </form> ";
}
?>
Below is the solution I found. Code is corrected accordingly.
foreach($room as $r) {
$result = mysqli_query($conn, "SELECT master_room_id FROM master_rooms WHERE master_room_name = '$r' ;");
$room_id_array = mysqli_fetch_array($result);
$room_id = $room_id_array[0]; // required as room_id goes into an array of length 1
$stmt = $conn->prepare("INSERT INTO user_room_list(user_info_id, master_room_id) VALUES (?, ?)");
$stmt->bind_param("si", $u_id, $room_id);
$stmt->execute();
I am creating a multiuser shared to do list application using PHP and MySQL. Currently, my application is displaying the to do list items by iterating over the database table with a while loop.
All of that works correctly, so I know I am connecting to the database. Part of the while loop also generates buttons that allow a user to "claim" an item that does not have anyone working on it or to indicate that at item has been completed. However, the buttons are not updating the database table.
<?php
include 'includes/dbh.inc.php';
$sql = 'SELECT * FROM items WHERE item_is_done = 0';
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$creator = $row['item_creator'];
$owner = $row['item_owner'];
$id = $row['item_id'];
if (isset($_POST['do_item'])) {
$update = "UPDATE items SET item_owner = $currentID WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=doing");
exit();
} else if(isset($_POST['complete_item'])) {
$update = "UPDATE items SET item_is_done = 1 WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=done");
exit();
}
echo '<h4>Item ID:</h4>' . $id . '<br><br>';
echo '<h4>Item created by:</h4>' . $creator . '<br><br>';
echo '<h4>Date Added: </h4>' . $row['item_add_date'] . '<br><br>';
echo '<h4>Item Title: </h4>' . $row['item_title'] . '<br><br>';
echo '<h4>Description: </h4>' . $row['item_description'] . '<br>';
if($row['item_owner'] == 'None') {
echo '<br>';
echo '<button type="submit" name="do_item" formaction="todo.php" formmethod="POST">Do Item</button>';
echo '<br>';
} else if($row['item_owner'] != 'None') {
echo '<br>';
echo '<h4>Item is being worked on by: </h4>' . $owner . '<br><br>';
echo '<button type="submit" name="complete_item" formaction="todo.php" formmethod="POST">Complete Item</button>';
echo '<br>';
}
echo '<hr>';
}
?>
I was also got stuck on same kind of problem what I did was I tried to put the updating variables in ' ' single quotes.
If it can help you you can try this queries
$update = "UPDATE items SET item_owner='$currentID' WHERE item_id='$id'";
$update = "UPDATE items SET item_is_done='1' WHERE item_id ='$id'";
I've got a problem with inserting multiple row to one table.
I've got a 3 tables:
1. student with id_student
2. ankieta with id_ankieta
3. student_ankieta with id_student and id_ankieta
I want to choose students from database using select or checkbox and choose one id_ankieta. After confirming, there are rows created in table (student_ankieta).
Now I can choose students but when I confirm, only one student gets added to the database.
Can anyone help me corect the code?
<?php
echo'<form method="post" action="student_ankieta.php">
<div class="box" style="margin:0 auto; top:0px;">
<h1>Student - ankieta:</h1>
<label>
<span><br/>Ankieta:</span>
</label>
<select class="wpis" name="id_ankieta">
<option>wybierz ankiete</option>';
$query = "SELECT * FROM ankieta";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id_ankieta'].'">' . $row{'rok_akademicki'}.' '. $row{'semestr_akademicki'}.' '.$row{'active_ankieta'} .'</option>';
}
echo '
</select>';
$query = "SELECT * FROM student";
$result = mysql_query($query);
echo'
<label>
<span><br/>Wybierz stundentów:</span>
</label>
<select multiple="multiple" name="id_student[]" size="10">';
while ($row = mysql_fetch_assoc($result))
{
echo '<option class="wpis" value="'.$row['id_student'].'" />'.$row{'pesel'}.' '. $row{'nazwisko'}.' '.$row{'imie'} .'</option>';
}
echo'<br/><input class="button" type="submit" value="Dodaj ankiete" name="dodaja">';
if(isset($_POST['dodaja']))
{
$id_ankieta = $_POST['id_ankieta'];
if(empty($_POST['id_ankieta']))
{
echo '<p style="margin-top:10px; font-size:75%; font-family: Calibri; color: red; text-align:center;">Musisz wypełnić wszystkie pola.</p>';
}
else
{
$id_student = $_POST['id_student'];
for ($i = 0; $i < count($id_student); $i++)
{
$id_student = $id_student[$i];
mysql_query("INSERT INTO student_ankieta (id_student, id_ankieta) VALUES ('" . $id_student . "','$id_ankieta')");
}
}
}
echo'</div></form>';?>
Put all students in to an array with the key = id_student
$query = "SELECT * FROM ankieta";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
students[$row['id_student']] = array($row['pesel'],$row['nazwisko'],$row['imie'];
}
If the form was posted the confirm will = 1 (from hidden input)
When first enter script "confirm will = 0
When zero, display all student with a check box with a name which includes the id_student in the format of n-i_student.
if intval($_POST['confirm']) = 0){
echo '<form action = "confirm.php" method="post"><input type="hidden" name="confirm" value="1"/><table>';
foreach ($students as $id => val){
echo "<tr><td><input type=\"checkbox\" name=\"n-$id\" value=\"1\" /> Select </div></td>$val[0]<td>$val[0]</td><td>$val[1]</td><td>$val[2]</td></tr>";
}
echo '</table></form>';
}
When confirm = 1
The checkboxes that were checked are inserted.
Check each post value for a key the starts with "n-"
get the rest of the key value after the n- for the id_student value.
Still 1 Major Problem, I do not know where to get the $id_ankieta'
And match it with the id_student.
I left that value as $val[???]
elseif intval($_POST['confirm']) = 1){
foreach ($_POST as $k =>$val){
if (inval($val) == 1 && substr($k,0,2) == 'n-'){
$id = substr($k,2);
$sql = mysql_query("INSERT INTO student_ankieta (id_student, id_ankieta) VALUES ('$id','" . $students[$id][$val[???]] . "')");
}
}
}