php mysql multiple select, dropdown menu, not saving back to db - php

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();

Related

If select option is unchecked, delete it from Database - Bootstrap Multiselect

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();
}

Passing 'id' from one php page to another php page

I have two Mysql tables "addcoupons" with one column(couponvalue) and two rows with values 50 and 100. Another table "paytoget" with one column(usercouponinhand).
I been trying to get all the rows in table-1 to a html page and pass the particular id of the row when user click on its value to anther php page where it inserts it in table-2. But unfortunately i have missed something which causing it to print id of first row irrespective of which value user clicks.
My code goes as:
Page 1 (user interaction page)
<br>
<?php
$sql2 = "SELECT * FROM addcoupons WHERE customernumber = '$mobile' ";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
$index = 0;
while($row2 = $result2->fetch_assoc()) {
$index++;
?>
<form action='usercouponadd.php?id=<?php echo $row2['id'];?>' method="post" id="usercouponadd">
<div>
<h4 class="amount" form="usercouponadd"> <strong>Rs. <?php echo ($row2["couponvalue"]); ?></strong></h4>
<button class="addbutton" form="usercouponadd" type="submit"><span> <strong>Add</strong> </span></button>
</div>
<hr class="line" align="left">
<?php }
} else {
echo "None";
}
?>
</div>
The second php page (insert into table-2)
$mobile = $_SESSION['mobile'];
$date = date('M-d,Y H:i:s');
$date2 = date('M-d,Y');
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT * FROM addcoupons WHERE id = " .$_GET["id"];
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
$index = 0;
while($row2 = $result2->fetch_assoc()) {
$index++;
$usercouponinhand = $row2["couponvalue"];
$sql = "INSERT INTO userpaytoget (usercouponinhand, mobile, date, date2)
VALUES ('$usercouponinhand', '$mobile', '$date', '$date2')";
if ($conn->query($sql) === TRUE) {
echo '<script language="javascript">';
echo 'alert("coupon has been successfully added")';
echo '</script>';
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
}
} else {
echo " ";
}
$conn->close();
Table-1 "addcoupons"
couponvalue
50
100
Table-2 "paytoget"
usercouponinhand
xx
xx
Any Help is Appreciated....
I guess i figured out the answer for "my" problem.
I just removed the form tag since i m not submitting any data from user, and added that addcoupon.php link to anchor link. it worked talking the particular id which user clicks..
Code goes like this::
<div>
<h4 class="amount" form="usercouponadd"> <strong>Rs. <?php echo ($row2["couponvalue"]); ?></strong></h4>
<a href="usercouponadd.php?id=<?php echo $row2['id'];?>" class="addbutton" >Add</a>
</div>
Thanks to all who took their time to give this problem a glance...

updating my database values through php

Hi I am trying to do a Registration that the users will put their name password and their answers to some questions and then an admin will manually answer to it if it's accepted.I did the system that loads their name password and answers in the database,and I also ran the things that will show the answers to the admin,but I can't figure a way to change a value just for one user not for all of them,I will leave you my codes and everything over here.
Here is my admin.viewapplications.php code
(Here,it shows everything fine,but I can't figure a way that the button to act just for one id not for all)
<?php
//include(__DIR__ . "/signup.php");
include("../resources/config.php");
//$name = $_POST['Name'];
//$mg = $_POST['MG'];
//$pg = $_POST['PG'];
//$rk = $_POST['RK'];
$sql = "SELECT id, name, tutorial, MG, PG, RK FROM rp_users WHERE tutorial = 2";
//$tutorial = "SELECT tutorial FROM rp_users";
$result = mysql_query($sql);
//$result2 = mysql_query($tutorial);
//$value = mysql_fetch_object($result2)
/*if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}*/
//if($value > 1)
//
while($row = mysql_fetch_array($result))
{
//$tutorial = row["tutorial"];
//f($tutorial == 2)
//}
$id = $row["id"];
$name = $row["name"];
$mg = $row["MG"];
$pg = $row["PG"];
$rk = $row["RK"];
echo "ID: " . $id."<br> <br>";
echo "Nume: " . $name."<br> <br>";
echo "MG: " . $mg."<br> <br>";
echo "PG: " . $pg."<br> <br>";
echo "RK: " . $rk."<br> <br>";
echo '<form action="./?p=applicationaccept" method="POST">';
echo '<input type="submit" name="accept" value="Accepta">';
echo '</form><br>';
echo '<form action="./?p=applicationdeny" method="POST">';
echo '<input type="submit" name="deny" value="Respinge">';
echo '</form><br> <br> <br>';
}
//}
//
?>
And here is my applicationaccept.php
<?php
include("../admin/admin.viewapplications.php");
include("../resources/config.php");
$iduser = $id;
$sql = "UPDATE rp_users SET tutorial=0";
$result = mysql_query($sql);
if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}
/*while($row = mysql_fetch_array($result))
{
}*/
?>
I think what you want to do is a simple UPDATE to your MySQL database..
but make sure you format the PHP code you're using otherwise it'll give you an ERROR!
Also you have to use 'mysqli' now in PHP!
<?php
$someID = '1';
$sql = "UPDATE `rp_users` SET `tutorial`= '0' WHERE `id` = $someID";
$result = mysqli_query($link, $sql);
if($result)
{
echo "Success";
}
else
{
echo ("Error");
}
?>
BTW I forgot to mntion the '$link' is the connection to your database!
As of my understanding of your question if your form action is applicationaccept.php and you are trying to update for one user in applicationaccept.php file, try this:
<?php
include("../admin/admin.viewapplications.php");
include("../resources/config.php");
$iduser = $_POST["id"]; // pass id as parameter in form
$sql = "UPDATE rp_users SET tutorial=0";// change this line to following line
$sql = "UPDATE rp_users SET tutorial=0 where id=$iduser";
$result = mysql_query($sql);
if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}
?>
Be aware your code is vulnerable

php insert to database row id and session id when click a button

How do I insert to the database when you click a button?
I also need to insert in the same command, the row [id] and SESSION [id]
I use an html page that calls the php, then the variaves SESSION are not in my php page. I'm stuck here .. please help
<?php
session_start();
if(!isset($_SESSION["email"]) || !isset($_SESSION["senha"])) {
header("Location: login.php");
exit;
}
?>
<?php
$deets = $_POST['deets'];
$deets = preg_replace('#[^0-9/]#i', '', $deets);
include ("connect.php");
$events = '';
$query = mysql_query('SELECT hora, status FROM horario');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$events .= '<div id="eventsControl"><button class="btn2" style=" float:right;" onMouseDown="overlay()"><b>Fechar</b></button><p><b> ' . $deets . '</b></p></div> <br />';
while($row = mysql_fetch_array($query)) {
$desc = $row['hora'];
$desc1 = "<input type='submit' class='btn1' name='insert' value='Marcar Hora' />";
$events .= '<div id="eventsBody">' . $desc . ' | '.$desc1. '<br /><hr><br /></div>';
}
}
echo $events;
if(isset($_REQUEST['insert']))
{
$SQL = "INSERT INTO eventos (id, data, idhora,) VALUES ('', '.$deets.', '$row[id]', 'session[id]')";
$result = mysql_query($SQL);
}
?>
2 Problems I initially see, although I don't have full context of your code.
First, I don't see you starting the session anywhere, this requires you to run session_start(); before you try to grab the session ID or save any variables into the session.
Second, as far as I understand it you'll need to reference the session id by doing something like this.
$id = session_id();

Resource id # 4 php

everytime i try and add one to the second column of a certain name, it changes the value to 5, if i echo my event it says it is equal to resource id #4. Anyone have any fixes?
<form action="new.php" method="POST">
<input type="text" name="input_value">
<br />
<input name="new_User" type="submit" value="Add to Users">
<input type="submit" name="event_Up" value="Attended Event">
<?php
//Connect to Database
mysql_connect("localhost", "root", "");
//If Add New user butten is clicked execute
if (isset($_POST['new_User']))
{
$username = $_POST['input_value'];
$make = "INSERT INTO `my_db`.`profile` (`Name`, `Events`) VALUES ('$username', '1')";
mysql_query($make);
}
//If Event up is pushed then add one
if (isset($_POST['event_Up']))
{
$username = $_POST['input_value'];
$event = mysql_query("SELECT 'Events' FROM `my_db`.`profile` WHERE Name ='$username'");
$newEvent = $event +1;
$update = "UPDATE `my_db`.`profile` SET Events = '$newEvent' WHERE Name = '$username'";
mysql_query($update);
}
//Print Table
$data = mysql_query("SELECT * FROM `my_db`.`profile`");
Print "<table border cellpadding=4>";
while($info = mysql_fetch_array($data))
{
Print "<tr>";
Print "<th>Name:</th> <td> ".$info['Name'] . "</td>";
Print "<th>Events:</th> <td>".$info['Events'] . " </td>";
}
Print "</table>";
?>
I've cleaned up your code a little bit.
It's still a mess, but should at least work (un-tested though).
<form action="new.php" method="post">
<input type="text" name="input_value">
<br />
<input name="new_User" type="submit" value="Add to Users">
<input type="submit" name="event_Up" value="Attended Event">
</form>
<?php
//Connect to Database
mysql_connect("localhost", "root", "");
//If Add New user butten is clicked execute
if (isset($_POST['new_User']))
{
$username = empty($_POST['input_value']) ? NULL : $_POST['input_value'];
if ( ! empty($username))
{
mysql_query("
INSERT INTO `my_db`.`profile`
(`Name`, `Events`)
VALUES
('". mysql_real_escape_string($username) ."', 1)
");
}
}
//If Event up is pushed then add one
if (isset($_POST['event_Up']))
{
$username = empty($_POST['input_value']) ? NULL : $_POST['input_value'];
if ( ! empty($username))
{
$event = mysql_query("
SELECT
Events
FROM
`my_db`.`profile`
WHERE
Name = '". mysql_real_escape_string($username) ."'
");
$newEvent = (int) (mysql_result($event, 0, 'Events') + 1);
mysql_query("
UPDATE
`my_db`.`profile`
SET
Events = $newEvent
WHERE
Name = '". mysql_real_escape_string($username) ."'
");
}
}
//Print Table
$data = mysql_query("SELECT * FROM `my_db`.`profile`");
Print "<table border cellpadding=4>";
while($info = mysql_fetch_assoc($data))
{
Print "<tr>";
Print "<th>Name:</th> <td> ". htmlentities($info['Name'], ENT_COMPAT, 'UTF-8') . "</td>";
Print "<th>Events:</th> <td>". htmlentities($info['Events'], ENT_COMPAT, 'UTF-8') . " </td>";
}
Print "</table>";
?>
Edit:
Just so you are aware... your issue was $newEvent = $event +1;.
$event is a MySQL resource, not the query's result. You have to use one of the mysql_* functions to get the data (see my code above.)
It seems you are just learning PHP, and I would highly recommend you stop using the mysql_* functions right now and start using PDO.
use mysql_fetch_assoc not mysql_fetch_array
any time you get a resource id rather than data it means you have just a pointer to something and most likely need a function call to get the data out.
You need to fetch the array and then define $event based on the results. You're assigning $events on the mysql query itself.
$result = mysql_query("SELECT 'Events' FROM `my_db`.`profile` WHERE Name ='$username'");
while($row = mysql_fetch_array( $result )) {
$event = $row['Events'];
}

Categories