I am trying to create a room availability check page for a hostel and I am having an issue.
I have a database with a table named 'rooms' listing all type of rooms with these rows:
id [INT]
name (room type) [CHAR]
capacity (max capacity, not to be changed)[INT]
used (number of beds used, I want to change this dynamically!) [INT]
I created a code to generate the rooms list from the DB with PHP and I want the "+" and "-" buttons to either add or remove one unit in the used column for a specific room. How can I do this?
Here is my code:
<!-- SOME HTML/PHP THAT WORKS -->
<?php if ($roomlist->num_rows > 0) {
// output data of each row
while($room = $roomlist->fetch_assoc()) {
$roomid = $room["id"]; ?>
<div>
<!-- SOME OTHER HTML/PHP THAT WORKS -->
// THE ISSUE IS BELOW, IT SHOWS THE CORRECT AMOUNT BUT $room["used"] DOES NOT UPDATE
<div>
Used: <?php echo $room["used"] . " / " . $room["capacity"] ?>
</div>
<div>
<form action="" method="POST">
<input type="submit" name="remove" value="-" />
<input type="submit" name="add" value="+" />
<?php
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
?>
</form>
</div>
</div>
</div>
<?php }
} else {
echo "0 results";
} ?>
If you set the action of your form to whatever the name of your code is (e.g., "rooms.php"), then move
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
up to the top so it updates the table before you query the table to fill in the rest of the page, it should work. Right now, your php is updating the table after the SELECT query to populate your page, so it doesn't appear to be updating.
I think a better tack would be implementing AJAX so your form updates the Used field without reloading the page.
Alright so I figured out a way on my own in the end so I post it here for other people facing a similar issue to overcome it ;)
Here is the concerned part of the code in index.php:
<form action="update.php?id=<?php echo $roomid ?>&action=remove&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="remove" class="minus" value="-" />
</form>
<form action="update.php?id=<?php echo $roomid ?>&action=add&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="add" class="plus" value="+" />
</form>
And the code of update.php:
if (isset($_REQUEST['used']) && isset($_REQUEST['id']) && isset($_REQUEST['capacity'])) {
$roomid = $_REQUEST['id'];
$used = $_REQUEST['used'];
$capacity = $_REQUEST['capacity'];
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') {
if ($used >= $capacity) {
header("location: index.php");
} else {
$newValue = $used + 1;
$add_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'remove') {
if ($used <= 0) {
header("location: index.php");
} else {
$newValue = $used - 1;
$remove_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
}
}
Related
i am trying to bulid an online attendace in php, i am fetching student list from student table, and want to put all chkboxs if checkd as present and if unchecked as absent,
i am unable to do that.
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
echo '<input type="checkbox" name="status" value="'.$id.'" checked>'.ucfirst($rows['f_name']).'';
}
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
it shows prefect students list, but i dont know how to set insert query for all of these chkboxes
try this query to insert from another table
SELECT * INTO TABLE2 FROM student
use where condition on student table as where student.column value to select checked values
Applied same above things with checkbox input field
echo '<input type="checkbox" name="status" value="'.$id.'" 'if($row['present_field_of_database']) ? 'checked' : ''
'>'.ucfirst($rows['f_name']).'';
it's fine then updated code with your problems i hope it's work for you
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
// if your $id value is right from $rows['id'] then
// change your student table name to the another table where available status of the student
$wh_sql = "SELECT * FROM student WHERE id=".$id;
$run_wh_sql = mysqli_query($conn, $wh_sql);
$Wh_rows = mysqli_fetch_assoc($run_wh_sql);
// add student present or absent value to the rows data
$rows['status'] = $Wh_rows['status'];
}
// set value as A or P respectively absent or present add jquery plugins for onclick event while client click on checkbox change value respectively
echo '<input type="checkbox" name="status" value="'.$rows['status'].'" 'if($rows['status'] == "A") ?'checked': '' '>'.ucfirst($rows['f_name']).' onclick= "$(this).val(this.checked ? P : A)"';
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
if (isset($_POST['send'])) {
$s_id = $_POST['status'];
$id = $_POST['student'];
if ($s_id) {
foreach ($s_id as $s) {
foreach ($id as $i) {
if (mysqli_query($conn, "INSERT INTO attendence(s_id,status) VALUES('".
mysqli_real_escape_string($conn, $s)."','".
mysqli_real_escape_string($conn, $i)."')")) {
$msg = "success";
}else{
$msg = "failed";
}
}
}
}
}
i have 3 students. when i press send it sends 9 entries. i am unable to understand how to insert all students data
This is attendance table
This is attandance table
i want to put entries like this if check box chekd it wil post p and if not it wil post a. i just need how to insert all sutdent at once quert
I have multiple fields on admin panel user can add field and delete the fields as well while adding it I placed simple insert query with foreach loop but it is difficult to understand the concept for updating that fields if user deletes a field or updates it is not working if I delete 1 field and update it it deletes 2 or more then 2 fields and when I try to update it is not updating well update issue is due i would be making some mistake with query. But main thing is about logic which I am unable to build it properly need help.
Update query
$video_link = $_POST['video_link'];
$old_links = count($video_link);
if(isset($_POST['video_id'])) {
$video_id = $_POST['video_id'];
$total_id = count($video_id);
} else {
$video_id = '';
}
$video_links = mysqli_query($connect, "SELECT * FROM video_slides WHERE model_id = '$model_id'");
$total_links = mysqli_num_rows($video_links);
$video_link = sizeof($video_link) - 1;
if($total_links >= 1) {
for($i = 0; $i<=$video_link; $i++) {
if(empty($video_id[$i])) {
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link``, `model_id`) VALUES ('$video_link[$i]', '$model_id')");
}
$query2 = mysqli_query($connect, "UPDATE `video_slides` SET `embeded_link`='$video_link[$i]' WHERE id='$video_id[$i]'");
if($video_link < $total_links) {
$new_total = $total_links-sizeof($video_link);
for($j = 0; $j<=$new_total; $j++) {
mysqli_query($connect, "DELETE FROM video_slides WHERE id='$video_id[$j]'");
}
}
}
} else {
for($i = 0; $i<=$video_link; $i++) {
if(empty($video_id[$i])) {
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link``, `model_id`) VALUES ('$video_link[$i]', '$model_id')");
}
}
}
And here is my form fields
<div class="form-group">
<label>Video Slides <input type="button" class="add_field_button btn blue" value="Add Field" /></label>
<div class="input_fields_wrap">
<?php
$sql3 = mysqli_query($connection, "SELECT * FROM video_slides WHERE model_id = '".$data['id']."'");
if(mysqli_num_rows($sql3) == 0) {
?>
<div class="new">
<input type="text" id="video_link" size="20" name="video_link[]" placeholder="Embeded Video Link" class="form-control" />
</div>
<?php
} else {
while($video = mysqli_fetch_assoc($sql3)) {
?>
<div class="new">
<input type="text" id="video_link" size="20" name="video_link[]" placeholder="Embeded Video Link" class="form-control" value="<?php echo $video['embeded_link']; ?>" />
<input type="hidden" value="<?php echo $video['id']; ?>" name="video_id[]" />
<a class="remove_field"><i class="fa fa-times"></i></a>
</div>
<?php } } ?>
</div>
</div>
As per my understanding you need only these thing why you making complex coding
$video_link = $_POST['video_link'];
//First Remove All ID
mysqli_query($connect, "DELETE FROM video_slides WHERE model_id='$model_id'");
//Then After insert updated data
foreach($video_link as $key=>$val){
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link`, `model_id`) VALUES ('$val', '$model_id')");
}
you should try to outsource your db connections in a separate class - this will lead to better readable code. An ORM like Doctrine can definitely help you to better understand your own code.
Hello my name is Patrick and this is my first question, i'm sorry but i'm not very good in PHP. probably there are more improvements but this post is for the questions. (but improvements are also welcome)
Question:
You can choose a team of 2 monsters // The monster are selected form database
The question is: if you choose 1 monster how can i fix that you can't choose the same monster on option 2?
PHP CODE:
Action of the 2 sumbit buttons
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if (isset($_POST['save'])) {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if($Result){
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5'){
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if($Result){
echo 'Team is aangepast!';
}
}
echo '';}
?>
Get the monsters form database and put it in a select list
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option4 = '';
while($row = mysql_fetch_assoc($get))
{
$option4 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
Show the selected item
<?php
$k4 = mysql_query("
SELECT user_team.m_keuze4, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze4=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row4 = mysql_fetch_assoc($k4))
{
$k4_1 = ''.$row4['m_keuze4'].' - '.$row4['monster'].' - '.$row4['type'].' - '.$row4['attack'].' - '.$row4['defense'].'';
}
?>
Option 5 is the same code as 4:
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option5 = '';
while($row = mysql_fetch_assoc($get))
{
$option5 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
<?php
$k5 = mysql_query("
SELECT user_team.m_keuze5, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze5=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row5 = mysql_fetch_assoc($k5))
{
$k5_1 = ''.$row5['m_keuze5'].' - '.$row5['monster'].' - '.$row5['type'].' - '.$row5['attack'].' - '.$row5['defense'].'';
}
?>
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form>
<form action="team.php" method="post">
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
In php the best you can do check the option once its posted:
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST,'option4') == filter_input(INPUT_POST,'option5')){
echo "Sorry. You can't select the same monster twice";
}else{
//your db insert logic goes here
}
}
It would be a good idea to also include some javascript to alert the user before they submit the form. This example uses jQuery
$('[name="option4"],[name="option5"]').change(function(){
if ($('[name="option4"]').val() == $('[name="option5"]').val()){
alert('you already chose that monster, please choose another');
}
});
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form> <!-- remove this line-->
<form action="team.php" method="post"> <!-- and this line-->
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$('[name="option4"],[name="option5"]').change(function () {
if ($('[name="option4"]').val() == $('[name="option5"]').val()) {
alert('you already chose that monster, please choose another');
}
});
});
</script>
Action of the 2 sumbit buttons
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST, 'option4') == filter_input(INPUT_POST, 'option5')) {
echo "Sorry. You can't select the same monster twice";
} else {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if ($Result) {
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5') {
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if ($Result) {
echo 'Team is aangepast!';
}
}
}
}
Edit again,
Demo Fiddle of js
Im trying to display 2 rows from my database but i want it to be that when i click the 1st row radiobuttons the 1st row updates.. this is not happening ... when i click the 1st row the second row updated .. check it yourself live please ---> http://albsocial.us/seria.php
<?php
include("connect.php");
$query = "SELECT * FROM test ORDER BY `id` DESC LIMIT 2";
$result = mysql_query($query);
echo "<h2>Seria A</h2><hr/>";
while($row = mysql_fetch_array($result)){
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo $home, " - ", $away,"<br/>";
echo "<form action='' method='post'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='radio' name='select' value='1'>1
<input type='radio' name='select' value='X'>X
<input type='radio' name='select' value='2'>2
<input type='submit' name='submit' value='Submit'/>
</form>
";
echo $home, " -> ", $win;
echo "<br/>Barazim -> ", $draw,"<br/>";
echo $away, " -> ", $lose,"<hr/>";
}
$id = isset($_POST['id']) && is_numeric($_POST['id']) ? $_POST['id']:false;
if (isset($_POST) && $_POST['select'] == 1){
$select = $_POST['select'];
$select = $win + $select;
mysql_query("UPDATE test SET win='$select' WHERE id='$id'");
header('Location: ../seria.php');
}else if (isset($_POST) && $_POST['select'] == 'X'){
$select = $_POST['select'];
$select = '1';
$select = $draw + $select;
mysql_query("UPDATE test SET draw='$select' WHERE id='$id'");
header('Location: ../seria.php');
}else if (isset($_POST) && $_POST['select'] == 2){
$select = $_POST['select'];
$select = '1';
$select = $lose + $select;
mysql_query("UPDATE test SET lose='$select' WHERE id='$id'");
header('Location: ../seria.php');
}
?>
the problem is with your button name. you should give each of your button name, a different name from each other so that the server will know which form is being submitted. you could try to give your button name based on id like this :
<input type='submit' name='submit<?php echo $id; ?>' value='Submit'/>
then you could do the conditional statement to see which button is clicked like this :
if ( isset( $_POST['submit$id'] ) ) { }
Your while loop will always leave $id set to the id of the last row in your dataset.
You'll need some way of submitting an id for each row in your form. Then, get that value when you retrieve POST variables.
If you structure things properly, you won't need to do a header redirect.
Also, I suggest moving the isset($_POST) test to it's own if statement, just so none of that code gets executed if nothing has been posted.
Here's how I would rework it:
<?php
include("connect.php");
// if data is submitted, update database
if (!empty($_POST)) {
$id = isset($_POST['id']) && is_numeric($_POST['id']) ? $_POST['id'] : false;
$select = isset($_POST['select'])&&in_array($_POST['select'],array('win','lose','draw')) ? $_POST['select'] : false;
if ($id && $select) {
$sql="UPDATE `test` SET `$select`=`$select`+1 WHERE `id`='$id';";
mysql_query($sql) or die(mysql_error());
}
}
// get data from database
$query = "SELECT * FROM test ORDER BY `id` DESC LIMIT 2";
$result = mysql_query($query) or die(mysql_error());
// output
?><h2>Seria A</h2><hr/><?php
while($row = mysql_fetch_assoc($result)){
?><p><?=$row['home']?> - <?=$row['away']?></p>
<form action="" method="post">
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="radio" name="select" value="win">1
<input type="radio" name="select" value="draw">X
<input type="radio" name="select" value="lose">2
<input type="submit" name="submit" value="Submit">
</form>
<p><?=$row['home']?> -> <?=$row['win']?></p>
<p>Barazim -> <?=$row['draw']?></p>
<p><?=$row['away']?> -> <?=$row['lose']?></p><?php
}
?>
Incidentally, how are you handling "home" vs "away" games?
I wanna update my product when there's user login. Here's my code in edit.php
<?php
$id= (int)$_GET['id'];
$query = "SELECT * FROM game WHERE gameId=".$id."";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs))
{
?>
<form action="doUpdate.php" method="post">
<?php echo "<image src=\"images/".$id.".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <input type="text" value="<?php echo $data['gameName'];?>" name="gameName"/></div>
<div class="myLabel">Developer</div><div>: <input type="text" value="<?php echo $data['gameDeveloper'];?>" name="gameDeveloper"/></div>
<div class="myLabel">Price</div><div>: <input type="text" value="<?php echo $data['gamePrice'];?>" name="gamePrice"/></div>
<br/>
<div id="txtError" style="color:#D70005">
<?php
if(isset($err))
{
if($err==1) echo"All Fields must be filled";
else if($err==2) echo"Price must be numeric";
else if($err==3) echo"Price must be between 1-10";
}
?>
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/></span>
<?php
}
?>
</form>
This is my code in doUpdate.php
<?php
$nama = $_POST['gameName'];
$dev = $_POST['gameDeveloper'];
$harga =$_POST['gamePrice'];
$id= (int)$_REQUEST['id'];
if($nama == "" || $dev == "" || $harga == "" )
{
header("location:edit.php?err=1");
}
else if(!is_numeric($harga))
{
header("location:edit.php?err=2");
}
else if($harga < 1 || $harga >10)
{
header("location:edit.php?err=3");
}
else
{
$query = "UPDATE game SET gameName='".$nama."', gameDeveloper='".$dev."', gamePrice=".$harga." where gameId=".$id."";
mysql_query($query);
header("location:product.php");
}
?>
Why I can't change name, developer, or price even I already give the action in form? And why if I delete the name, developer, and price to know wether the validation works or not, it said that Undefined index in edit.php $id= (int)$_GET['id']; ?
You are trying to get $_REQUEST['id'] in doUpdate.php but there is no such field in the form.
You have to add it as a hidden field.
Also you have to format your strings.
Every string you're gonna put into query you have to escape special characters in.