function unable to call WHERE id = $id - php

I'm trying to do a multiple edit function, the code goes through but the database is not updated. I figure the problem is that at WHERE id = $id no value gets called out because if I replace $id with an actual id e.g. id = 001 the entry 001 gets updated.
This page selects which entries get edited
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " . "FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (date("Y-m-d") > $row['start_date'] && date("Y-m-d") < $row['end_date']) {
echo "<tr><th>" . "<input type = 'checkbox' name = 'checkbox2[]' value='" . $row['crew_name']. "' >" . "</th>";
echo "<th>" . "" . $row["crew_name"] . "";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
} else {
}
}
?>
This is the edit page
<?php include 'header.php'; ?>
<div id="container4"><?php
require ("dbfunction.php");
$con = getDbConnect();
$checkbox2 = $_POST['checkbox2'];
if (!mysqli_connect_errno($con)) {
$str = implode($checkbox2);
$queryStr = "SELECT * " .
"FROM crewlist WHERE ($str) && crew_id";
}
$result = mysqli_query($con, $queryStr);
?><form action="handlemultiedit.php" method="post"><?php
if ($_POST['submit']) {
$checkbox2 = $_POST['checkbox2'];
foreach ($checkbox2 as $crewname) {
?>
<input type="hidden" name="crew_id" value="<?php $id = isset($_GET['id']) ? $_GET['id'] : ''; ?>" />
<?php echo "<tr><th>" . $crewname . ":</th><br>";
echo " <tr>
<td>Shift 1:</td>
<td><input type=\"time\" name=\"start_hour\" value=\"start_hour\" id=\"start_hour\" step=\"1800\" required> to <input type=\"time\" name=\"end_hour\" value=\"end_hour\" id=\"end_hour\" step=\"1800\" required>
</td>
</tr>
<tr>
<td>Shift 2:</td>
<td><input type=\"time\" name=\"start_hour2\" value=\"start_hour2\" id=\"start_hour2\" step=\"1800\" required> to <input type=\"time\" name=\"end_hour2\" value=\"end_hour2\" id=\"end_hour2\" step=\"1800\" required>
</td>
</tr><br><br>";
?><?php
}?><td><input type="submit" value="Submit" ></td></form><?php
}
?>
print_r($_POST);
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$start_hour = $_POST["start_hour"];
$end_hour = $_POST["end_hour"];
$start_hour2 = $_POST["start_hour2"];
$end_hour2 = $_POST["end_hour2"];
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET start_hour = '$start_hour',end_hour = '$end_hour', start_hour2 = '$start_hour2',end_hour2 = '$end_hour2' WHERE crew_id = $crew_id";
mysqli_query($con, $sqlQueryStr);
}
//header('Location: crewlisting.php');
mysqli_close($con);
?>

Try placing single quotes (i.e. 's) around your final variable in your statement, as you have done with all of your other variables, i.e. change it to "WHERE crew_id = '$crew_id'";

Related

How can I execute multiple prepared SQL statements from a single input button press in php?

Context: The page is for menu item entry into an order. When a menu item button is pressed, data from 'theProducts' table is queried and inserted into 'theOrderItems' table. I also want the same button press to take the serving size value (theProducts.dbProdServing) and subtract that amount from the product's inventory (theInventory.dbInventoryAmt), and update that table accordingly.
The problem I'm having is trying to figure out how to have one button press execute two prepared statements with bound values at the same time, those being the statement that INSERTS product data into 'theOrderItems' table and the statement that UPDATEs 'theInventory' table.
Currently, the page runs the INSERT statement fine, but the UPDATE statement doesn't run at all.
There are three pages that handle the entire order system, 'insertOrder.php' opens the order, 'insertOrderItem.php' allows the adding of items to a specific order, and 'completeorder.php' just displays the total order. I'll only post the first two pages.
insertOrder.php
<?php
$pagetitle = 'Insert Order';
require_once 'header.php';
require_once 'connect.php';
$errormsg = "";
$showform = 1;
$sqlselectt = "SELECT * from theTables";
$resultt = $db->prepare($sqlselectt);
$resultt->execute();
$sqlselectc = "SELECT * from theCustomers";
$resultc = $db->prepare($sqlselectc);
$resultc->execute();
$sqlselects = "SELECT * from theStaff";
$results = $db->prepare($sqlselects);
$results->execute();
$sqlselectl = "SELECT * from theLocations";
$resultl = $db->prepare($sqlselectl);
$resultl->execute();
if( isset($_POST['thesubmit']) )
{
$formfield['ffOrderPickup'] = $_POST['orderPickup'];
$formfield['ffCustKey'] = $_POST['custKey'];
$formfield['ffTableKey'] = $_POST['tableKey'];
$formfield['ffStaffKey'] = $_POST['staffKey'];
$formfield['ffLocationKey'] = $_POST['locationKey'];
$formfield['ffOrderDate'] = $_POST['orderDate'];
$formfield['ffOrderTime'] = $_POST['orderTime'];
if(empty($formfield['ffCustKey'])){$errormsg .= "<p>The customer field is empty.</p>";}
if(empty($formfield['ffTableKey'])){$errormsg .= "<p>The table field is empty.</p>";}
if(empty($formfield['ffStaffKey'])){$errormsg .= "<p>The employee field is empty.</p>";}
if(empty($formfield['ffLocationKey'])){$errormsg .= "<p>The location field is empty.</p>";}
if(empty($formfield['ffOrderDate'])) {$errormsg .= "<p>The order entry date is not selected.</p>"; }
if(empty($formfield['ffOrderTime'])) {$errormsg .= "<p>The order entry time is not selected.</p>"; }
if($errormsg != "")
{
echo "<div class='error'><p>THERE ARE ERRORS!</p>";
echo $errormsg;
echo "</div>";
}
else
{
$sqlmax = "SELECT MAX(dbOrderKey) AS maxKey FROM theOrders";
$resultmax = $db->prepare($sqlmax);
$resultmax->execute();
$rowmax = $resultmax->fetch();
$maxKey = $rowmax['maxKey'];
$maxKey = $maxKey + 1;
try
{
$sqlinsert = 'INSERT INTO theOrders (dbOrderKey, dbCustKey, dbTableKey, dbStaffKey, dbLocationKey, dbOrderComplete, dbOrderDate, dbOrderTime, dbOrderMade, dbOrderPickup)
VALUES (:bvOrderKey, :bvCustKey, :bvTableKey, :bvStaffKey, :bvLocationKey, 0, :bvOrderDate, :bvOrderTime, 0, :bvOrderPickup)';
$stmtinsert = $db->prepare($sqlinsert);
$stmtinsert->bindvalue(':bvOrderKey', $maxKey);
$stmtinsert->bindvalue(':bvCustKey', $formfield['ffCustKey']);
$stmtinsert->bindvalue(':bvTableKey', $formfield['ffTableKey']);
$stmtinsert->bindvalue(':bvStaffKey', $formfield['ffStaffKey']);
$stmtinsert->bindvalue(':bvLocationKey', $formfield['ffLocationKey']);
$stmtinsert->bindvalue(':bvOrderDate', $formfield['ffOrderDate']);
$stmtinsert->bindvalue(':bvOrderTime', $formfield['ffOrderTime']);
$stmtinsert->bindvalue(':bvOrderPickup', $formfield['ffOrderPickup']);
$stmtinsert->execute();
echo "<p>Order Number: " . $maxKey . "</p>";
echo "<p>Location: " . $formfield['ffLocationKey'] . "</p>";
echo '<br><br><form action="insertOrderItem.php" method="post">';
echo '<input type="hidden" name="orderKey" value="' . $maxKey . '">';
echo '<input type="hidden" name="locationKey" value="' . $formfield['ffLocationKey'] . '">';
echo '<input type="submit" name="submit" value="Enter Order Items">';
echo '</form>';
$showform = 0;
}
catch(PDOException $e)
{
echo 'ERROR!!!' .$e->getMessage();
exit();
}
}
}
if ($visible == 1 && $showform == 1)
{
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="theform">
<fieldset><legend>Order Information</legend>
<table border>
<tr>
<th><label for="custKey">Customer:</label></th>
<td><select name="custKey" id="custKey">
<option value = "">Please Select a Customer</option>
<?php while ($rowc = $resultc->fetch() )
{
echo '<option value="'. $rowc['dbCustKey'] . '">' . $rowc['dbCustLast'] . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th><label for="tableKey">Table:</label></th>
<td><select name="tableKey" id="tableKey">
<option value = "">Please Select a Table</option>
<?php while ($rowt = $resultt->fetch() )
{
echo '<option value="'. $rowt['dbTableKey'] . '">' . $rowt['dbTableKey'] . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th><label for="staffKey">Employee:</label></th>
<td><select name="staffKey" id="staffKey">
<option value = "">Please Select an Employee</option>
<?php
while ($rows = $results->fetch() )
{
if($_SESSION['userid'] == $rows['dbStaffKey']) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="'. $rows['dbStaffKey'] . '" ' . $selected . '>' . $rows['dbStaffLast'] . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th><label for="locationKey">Location:</label></th>
<td><select name="locationKey" id="locationKey">
<option value = "">Please Select an Location</option>
<?php
while ($rowl = $resultl->fetch() )
{
echo '<option value="'. $rowl['dbLocationKey'] . '" ' . $selected . '>' . $rowl['dbLocationCity'] . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th>Pick a Delivery Type:</th>
<td><input type="radio" name="orderPickup" id="orderPickup"
value=1 <?php echo ' checked';?> />
<label for="pickup">Pickup</label>
<input type="radio" name="orderPickup" id="orderPickup"
value=0 />
<label for="inHouse">In-House</label>
</td>
</tr>
<tr>
<th><label for="orderDate">Entry Date:</label></th>
<td><input type="date" name="orderDate" id="orderDate" value="<?php if( isset($formfield['ffOrderDate'])){echo $formfield['ffOrderDate'];}?>" /></td>
</tr>
<tr>
<th><label for="orderTime">Entry Time:</label></th>
<td><input type="time" name="orderTime" id="orderTime" value="<?php if( isset($formfield['ffOrderTime'])){echo $formfield['ffOrderTime'];}?>" /></td>
</tr>
</table>
<input type="submit" name = "thesubmit" value="Enter">
</fieldset>
</form>
<br><br>
<?php
}
include_once 'footer.php';
?>
insertOrderItem.php
<?php
$pagetitle = 'Insert Order Items';
require_once 'header.php';
require_once 'connect.php';
$formfield['ffOrderKey'] = $_POST['orderKey'];
$formfield['ffProdKey'] = $_POST['prodKey'];
$formfield['ffProdPrice'] = $_POST['prodPrice'];
$formfield['ffProdServing'] = $_POST['prodServing'];
$formfield['ffLocationKey'] = $_POST['locationKey'];
$sqlselectc = "SELECT * FROM theCategories";
$resultc = $db->prepare($sqlselectc);
$resultc->execute();
$sqlselecti = "SELECT * FROM theInventory";
$resulti = $db->prepare($sqlselecti);
$resulti->execute();
if (isset($_POST['OIEnter'])) {
$rowi = $resulti->fetch();
$invRem = $rowi['dbInventoryAmt'] - $formfield['ffProdServing'];
$sqlinsert = 'INSERT INTO theOrderItems (dbOrderKey, dbProdKey, dbProdPrice)
VALUES (:bvOrderKey, :bvProdKey, :bvProdPrice)';
$stmtinsert = $db->prepare($sqlinsert);
$stmtinsert->bindValue(':bvOrderKey', $formfield['ffOrderKey']);
$stmtinsert->bindValue(':bvProdKey', $formfield['ffProdKey']);
$stmtinsert->bindValue(':bvProdPrice', $formfield['ffProdPrice']);
$stmtinsert->execute();
$sqlupdate = "UPDATE theInventory
SET dbInventoryAmt = :bvInventoryAmt
WHERE dbLocationKey = :bvLocationKey
AND dbProdKey = :bvProdKey";
$stmtupdate = $db->prepare($sqlupdate);
$stmtupdate->bindValue(':bvInventoryAmt', $invRem);
$stmtupdate->bindValue(':bvLocationKey', $formfield['ffLocationKey']);
$stmtupdate->bindValue(':bvProdKey', $formfield['ffProdKey']);
$stmtupdate->execute();
}
if (isset($_POST['DeleteItem'])) {
$sqldelete = "DELETE FROM theOrderItems WHERE dbOrderItemKey = :bvOrderItemKey";
$stmtdelete = $db->prepare($sqldelete);
$stmtdelete->bindValue(':bvOrderItemKey', $_POST['orderItemKey']);
$stmtdelete->execute();
}
if (isset($_POST['UpdateItem'])) {
$formfield['ffProdPrice'] = trim($_POST['newProdPrice']);
$formfield['ffOrderNotes'] = trim($_POST['newOrderNote']);
$sqlupdateoi = 'UPDATE theOrderItems
SET dbProdPrice = :bvProdPrice,
dbOrderNotes = :bvOrderNotes
WHERE dbOrderItemKey = :bvOrderItemKey';
$stmtupdateoi = $db->prepare($sqlupdateoi);
$stmtupdateoi->bindValue(':bvOrderItemKey', $_POST['orderItemKey']);
$stmtupdateoi->bindValue(':bvProdPrice', $formfield['ffProdPrice']);
$stmtupdateoi->bindValue(':bvOrderNotes', $formfield['ffOrderNotes']);
$stmtupdateoi->execute();
}
$sqlselecto = 'SELECT theOrderItems.*, theProducts.dbProdName, theProducts.dbProdServing, theCategories.*
FROM theOrderItems, theProducts, theCategories
WHERE theOrderItems.dbProdKey = theProducts.dbProdKey
AND theProducts.dbCatKey = theCategories.dbCatKey
AND theOrderItems.dbOrderKey = :bvOrderKey';
$resulto = $db->prepare($sqlselecto);
$resulto->bindValue(':bvOrderKey', $formfield['ffOrderKey']);
$resulto->execute();
if($visible == 1 && ($_SESSION['userpermit'] == 1 || $_SESSION['userpermit'] == 3 || $_SESSION['userpermit'] == 4))
{
?>
<fieldset><legend><b>Enter Items for Order Number: <?php echo $formfield['ffOrderKey']; ?></b></legend>
<table border>
<?php
$counter = 0;
echo '<tr><b>';
while ($rowc = $resultc->fetch()){
if ($counter == 2){
echo '</tr><tr>';
$counter = 0;
}
$counter++;
echo '<th valign = "middle" align = "center">' . $rowc['dbCatName'] . '<br> <table border>';
$sqlselectp = "SELECT * FROM theProducts WHERE dbCatKey = :bvCatKey";
$resultp = $db->prepare($sqlselectp);
$resultp->bindValue(':bvCatKey', $rowc['dbCatKey']);
$resultp->execute();
while ($rowp = $resultp->fetch()){
echo '<td>';
echo '<form action = "' . $_SERVER['PHP_SELF'] . '" method = "post">';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "hidden" name = "prodKey" value = "' . $rowp['dbProdKey'] . '">';
echo '<input type = "hidden" name = "prodPrice" value = "' . $rowp['dbProdPrice'] . '">';
echo '<input type = "hidden" name = "prodServing" value = "'. $rowp['dbProdServing'] . '">';
echo '<input type = "submit" id="order" name = "OIEnter" value = "' . $rowp['dbProdName'] . '">';
echo '</form>';
echo '</td>';
}
echo '</table></th>';
}
echo '</tr>';
?>
</table>
</table>
</fieldset>
<br><br>
<table>
<tr>
<td>
<table border>
<tr>
<th>Item</th>
<th>Category</th>
<th>Description</th>
<th>Serving Size</th>
<th>Price</th>
<th>Notes</th>
<th></th>
<th></th>
</tr>
<?php
$ordertotal = 0;
while ($rowo = $resulto->fetch()){
$ordertotal = $ordertotal + $rowo['dbProdPrice'];
echo '<tr><td>' . $rowo['dbProdName']
. '</td><td>' . $rowo['dbCatName']
. '</td><td>' . $rowo['dbProdDesc']
. '</td><td>' . $rowo['dbProdServing']
. '</td><td>' . $rowo['dbProdPrice']
. '</td><td>' . $rowo['dbOrderNotes']
. '<td>';
echo '<form action = "' . $_SERVER['PHP_SELF'] . '" method = "post">';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "hidden" name = "orderItemKey" value = "' . $rowo['dbOrderItemKey'] . '">';
echo '<input type = "submit" name = "NoteEntry" value = "Update">';
echo '</form></td><td>';
echo '<form action = "' . $_SERVER['PHP_SELF'] . '" method = "post">';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "hidden" name = "orderItemKey" value = "' . $rowo['dbOrderItemKey'] . '">';
echo '<input type = "submit" name = "DeleteItem" value = "Delete">';
echo '</form></td></tr>';
}
echo '<tr><th></th><th></th><th>Total</th><th>' . $ordertotal . '</th><th></th><th></th><th></th></tr>';
?>
</table>
<?php
if(isset($_POST['NoteEntry'])){
$sqlselectoi = 'SELECT theOrderItems.*, theProducts.dbProdName
FROM theOrderItems, theProducts
WHERE theOrderItems.dbProdKey = theProducts.dbProdKey
AND theOrderItems.dbOrderItemKey = :bvOrderItemKey';
$resultoi = $db->prepare($sqlselectoi);
$resultoi->bindValue(':bvOrderItemKey', $_POST['orderItemKey']);
$resultoi->execute();
$rowoi = $resultoi->fetch();
echo '</td><td>';
echo '<form action = "' . $_SERVER['PHP_SELF'] . '" method = "post">';
echo '<table>';
echo '<tr><td>Price: <input type="text" name = "newProdPrice" value = "' .
$rowoi['dbProdPrice'] . '"></td></tr>';
echo '<tr><td>Notes: <input type="text" name = "newOrderNote" value = "' .
$rowoi['dbOrderNotes'] . '"></td></tr>';
echo '<tr><td>';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "hidden" name = "orderItemKey" value = "' . $rowoi['dbOrderItemKey'] . '">';
echo '<input type = "submit" name = "UpdateItem" value = Update Item">';
echo '</td></tr></table>';
}
?>
</td></tr>
</table>
<br><br>
<?php
echo '<form action = "completeorder.php" method = "post">';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "submit" name = "CompleteOrder" value = "Complete Order">';
echo '</form>';
}
include_once 'footer.php';
?>

PHP database delete function only works on first row of database?

<p><?php include 'header.php'; ?></p>
<div align="justify">
<td>Name:<input type="text" name="password" ></td> <!-- database -->
<td> Rank:<select>
<!--<option value="volvo">//Database</option>
<option value="saab">Saab</option>
-->
<?php
require ("dbfunction.php");
$con = getDbConnect();
<td> <input type="checkbox" name="vehicle" value="Bike">Group by Rank</td> <!-- database -->
<td> <input type="checkbox" name="vehicle" value="Bike">Include previous service terms</td> <!-- database -->
</div>
<p><table>
<tr>
<th>Name</th>
<th>Rank</th>
<th>Start Date</th>
<th>End Date</th>
<th>Watchkeeping</th>
<th>Active</th>
<th></th>
<th></th>
</tr> <!-- database -->
<tr> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
//echo "<div><a href=http://localhost/poshproject/crewlisting.php?crew_name={$row["crew_id"]}>";
echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
echo "<td>Edit";
//echo "<td><center><button type=\"submit\" name=\"Delete\" value="' . $row['crew_id'].'"/>Delete</button></center></td>";
echo "<td>Delete";
}
?>
<!--
<td><center><button type="submit" value="Edit">Edit</button></center></td>
<td><center><button type="submit" value="Delete">Delete</button></center></td>-->
</form></tr>
</tr>
</table>
---------------------delete.php---------------------
<?php
//print_r($_GET);
include 'dbfunction.php';
$con = getDbConnect();
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (!mysqli_connect_errno($con)) {
$sqliQueryStr = "DELETE FROM `posh`.`crewlist` WHERE crew_id = ". $row['crew_id'] . "";
}
mysqli_query($con, $sqliQueryStr);
header('Location: crewlisting.php');
mysqli_close($con);
//echo "user has been deleted";
}
?>
Delete function only works on first row of database. When I delete the rows that are not the first, it deletes the first row instead. Not sure where the error is when I've tried pretty much everything.
I think you are wrong on delete.php file. Put below code in your delete.php file.
---------------------delete.php---------------------
<?php
include 'dbfunction.php';
$con = getDbConnect();
if (!mysqli_connect_errno($con)) {
$sqliQueryStr = "DELETE FROM `posh`.`crewlist` WHERE crew_id = " . $_GET['id'];
mysqli_query($con, $sqliQueryStr);
}
header('Location: crewlisting.php');
mysqli_close($con);
Change your delete query as below
$sqliQueryStr = "DELETE FROM `posh`.`crewlist` WHERE crew_id = " . $_GET['id'] . "";

php update mysql table via form, reload information on page immediately

I'm creating a page in which room reservations are displayed in a table, with the possibilty to update or delete them.
The reservations come from a MySQL-database, table reservations.
It works, but I would like that the information from the database is updated on the page immediately after pressing the buttons.
For instance, if now I set the username from 'person' to 'another person', the field gets updated correctly in the database, but I need to refresch the page to see the update in my table.
How can I do this?
<table border="1">
<tr><td>Datum</td><td>Start</td><td>Stop</td><td>Gebruikersnaam</td></tr>
<?php
$now = date("Y-m-d");
$query = "SELECT * FROM reservations WHERE (roomid = " . 45 . " AND end > NOW() ) ORDER BY start";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$reservationid=$row["reservationid"];
$username=$row["username"];
$aantal=$row["numberingroup"];
$reservationid=$row["reservationid"];
$start=$row["start"];
$end=$row["end"];
$roomid=$row["roomid"];
?>
<form action="" method="post">
<tr><td><input name="StartDate" value="<? echo $StartDate; ?>" /></td><td><input name="StartTime" value="<? echo $StartTime; ?>" /></td><td><input name="StopTime" value="<? echo $StopTime; ?>" /></td><td><input name="username" value="<? echo $username;?>" /></td><td><input type="submit" value="update" name="<?php echo 'update_' . $reservationid; ?>" /></td><td><input type="submit" value="delete" name="<?php echo 'delete_' . $reservationid; ?>" /></td><td><? echo $reservationid; ?></td></tr></form>
<?php
//DELETE
if(isset($_POST['delete_' . $reservationid]))
{
$deletequery = "DELETE FROM reservations WHERE reservationid=" . $reservationid;
if(mysql_query($deletequery)){
echo "<p><b>Boeking verwijderd</b></p>";}
else {
echo "<p><b>Boeking niet verwijderd</b></p>";}
}
//UPDATE
if(isset($_POST['update_' . $reservationid]))
{
$NewStartDate = explode("-",$_POST[StartDate]);
$newstartdate = $NewStartDate[2] . "-" . $NewStartDate[1] . "-" . $NewStartDate[0];
$newstarttime = $_POST[StartTime] . ":00";
$newenddate = $newstartdate;
$NewEndTime = explode(":",$_POST[StopTime]);
$newendtime = mktime($NewEndTime[0],($NewEndTime[1]-1),59);
$newendtime = date("H:i:s",$newendtime);
$UpdateStart = $newstartdate . " " . $newstarttime;
$UpdateEnd = $newenddate . " " . $newendtime;
$UpdateUsername = $_POST[username];
$updatequery = "UPDATE reservations SET start='$UpdateStart', end='$UpdateEnd', username='$UpdateUsername' WHERE reservationid=" . $reservationid;
if(mysql_query($updatequery)){
echo "<p><b>Updated " . $reservationid . " " . $UpdateStart . " " . $UpdateEnd . " " . $UpdateUsername . "</b></p>";}
else {
echo "<p><b>FAILURE IS NOT AN OPTION. AGAIN!</b></p>";}
}
?>
<?php
}
mysql_close();
?>
The working code is:
<?php
//DELETE
if(isset($_POST['delete_' . $_POST[updateid]]))
{
$deletequery = "DELETE FROM reservations WHERE reservationid=" . $_POST[updateid];
if(mysql_query($deletequery)){
echo "<p><b>Boeking verwijderd</b></p>";
}
else {
echo "<p><b>FAILURE IS NOT AN OPTION. AGAIN!</b></p>";
}
}
//UPDATE
if(isset($_POST['update_' . $_POST[updateid]]))
{
$UpdateID = $_POST[updateid];
$NewStartDate = explode("-",$_POST[StartDate]);
$newstartdate = $NewStartDate[2] . "-" . $NewStartDate[1] . "-" . $NewStartDate[0];
$newstarttime = $_POST[StartTime] . ":00";
$newenddate = $newstartdate;
$NewEndTime = explode(":",$_POST[StopTime]);
$newendtime = mktime($NewEndTime[0],($NewEndTime[1]-1),59);
$newendtime = date("H:i:s",$newendtime);
$UpdateStart = $newstartdate . " " . $newstarttime;
$UpdateEnd = $newenddate . " " . $newendtime;
$UpdateUsername = $_POST[username];
$updatequery = "UPDATE reservations SET start='$UpdateStart', end='$UpdateEnd', username='$UpdateUsername' WHERE reservationid='$UpdateID'";
if(mysql_query($updatequery)){
echo "<p><b>Updated " . $reservationid . " " . $UpdateStart . " " . $UpdateEnd . " " . $UpdateUsername . "</b></p>";
}
else {
echo "<p><b>FAILURE IS NOT AN OPTION. AGAIN!</b></p>";
}
// echo "<p><b>Updated " . $reservationid . " " . $UpdateStart . " " . $UpdateEnd . " " . $UpdateUsername . "</b></p>";
}
?>
<?php
$query = "SELECT * FROM reservations WHERE (roomid = " . 45 . " AND end > NOW() ) ORDER BY start";
$result = mysql_query($query) or die(mysql_error());
?>
<table border="1">
<tr><td>Datum</td><td>Start</td><td>Stop</td><td>Gebruikersnaam</td></tr>
<?php
while($row = mysql_fetch_array($result)){
$reservationid=$row["reservationid"];
$username=$row["username"];
$aantal=$row["numberingroup"];
$reservationid=$row["reservationid"];
$start=$row["start"];
$end=$row["end"];
$roomid=$row["roomid"];
$startdate = explode(" ",$start);
$startdate[0] = explode("-",$startdate[0]);
$startdate[1] = explode(":",$startdate[1]);
$StartFormat = mktime($startdate[1][0],$startdate[1][1],$startdate[1][2],$startdate[0][1],$startdate[0][2],$startdate[0][0]);
$StartDate = date("d-m-Y",$StartFormat);
$StartTime = date("H:i",$StartFormat);
$stopdate = explode(" ",$end);
$stopdate[0] = explode("-",$stopdate[0]);
$stopdate[1] = explode(":",$stopdate[1]);
$StopFormat = mktime($stopdate[1][0],$stopdate[1][1],($stopdate[1][2]+1),$stopdate[0][1],$stopdate[0][2],$stopdate[0][0]);
$StopDate = date("d-m-Y",$StopFormat);
$StopTime = date("H:i",$StopFormat);
?>
<form action="" method="post">
<tr><td><input type="hidden" name="updateid" value="<?php echo $reservationid; ?>" /> <input name="StartDate" value="<? echo $StartDate; ?>" /></td><td><input name="StartTime" value="<? echo $StartTime; ?>" /></td><td><input name="StopTime" value="<? echo $StopTime; ?>" /></td><td><input name="username" value="<? echo $username;?>" /></td><td><input type="submit" value="update" name="<?php echo 'update_' . $reservationid; ?>" /></td><td> <input type="submit" value="delete" name="<?php echo 'delete_' . $reservationid; ?>" /></td> </tr>
</form>
<?php
}
mysql_close();
?>
</table>
Move the logic that does the updating and deleting above the logic that does the rendering:
<?php
// DELETE (your delete stuff)
// UPDATE (your update stuff)
// RETRIEVE (your SELECT query)
?>
<table> <!-- your table markup -->
<?php
// RENDER (your while loop and such)
You'll also need to adjust your logic a bit. You're using the $reservationid from the SELECT to do the deleting and updating. This doesn't work, because the execution context for the PHP is refreshed with each page load. What you need is to store the reservation id in each form (maybe in a hidden field), and then to retrieve that from $_POST.
Incidentally, your code is very vulnerable to SQL injection. Also, you should look at using mysqli or PDO; mysql_connect is deprecated in the current version of PHP.
You could use jQuery for this. You have to make an $.ajax (http://api.jquery.com/jquery.ajax/) call. From the callback you can fill/set the fields you want to. You'll need $('#idofelement').html()(http://api.jquery.com/html/) for this. If you have got any questions don't be affraid to ask ;) Good luck!

php file takes long time loading then returns blank page mysqli

I'm trying to display the elements of an event in a form for the user to edit. I want the current values to be entered or selected, but I want it in a way so that I don't have to validate all sorts of info. I have a calendar picker and want to use dropdowns for the times. This code hangs for a few minutes and then returns a completely blank page. Am I just overloading the server with all the queries or is there something wrong with my code?
$id = $_POST['id'];
/* Edit Event Form */
echo '<form action="edit-event-process.php" method="post">';
echo '<center><table style="text-align:center">';
/* Set up queries individually to allow for dropdowns for hour, minute, am/pm, category */
/************* Query for Name *******************/
$queryName = mysqli_query($link, "SELECT Name FROM events WHERE id = " . $id);
while($rowName = mysqli_fetch_assoc($queryName)){
foreach($rowName as $keyName => $valName){
echo '<tr><td>Name: </td><td><input type="text" id="Name" name="Name" value="' . $valName . '"></td></tr>';
}
}
/************* Query for Description **************/
$queryDesc = mysqli_query($link, "SELECT Description FROM events WHERE id = " . $id);
while($rowDesc = mysqli_fetch_assoc($queryDesc)){
foreach($rowDesc as $keyDesc => $valDesc){
echo '<tr><td>Description: </td><td><input type="text" id="Description" name="Description" value="' . $valDesc . '"></td></tr>';
}
}
/************* Query for Start Date ***************/
$queryStDt = mysqli_query($link, "SELECT StartDate FROM events WHERE id = " . $id);
while($rowStDt = mysqli_fetch_assoc($queryStDt)){
foreach($rowStDt as $keyStDt => $valStDt){
echo '<tr><td>Start Date: </td><td><input type="text" id="StartDate" name="StartDate" value="' . $valStDt . '"></td></tr>';
}
}
/************* Query for All Day **************/
$queryAllDay = mysqli_query($link, "SELECT AllDay FROM events WHERE id = " . $id);
while($rowAllDay = mysqli_fetch_assoc($queryAllDay)){
foreach($rowAllDay as $keyAllDay => $valAllDay){
if ($valAllDay == '1'){
echo '<tr><td>All Day? </td><td><input type="checkbox" id="AllDay" name="AllDay" checked="checked"></td></tr>';
}
else {
echo '<tr><td>All Day? </td><td><input type="checkbox" id="AllDay" name="AllDay"></td></tr>';
}
}
}
/************/
echo '<div id="dates">';
/************/
/************* Query for Start Hour ****************/
echo '<tr><td>Start Hour</td><td><select name="StartHour" id="StartHour">';
$queryStHr = mysqli_query($link, "SELECT TIME_FORMAT(StartTime, '%h') AS StartHour WHERE id = " . $id);
while ($rowStHr = mysqli_fetch_assoc($resultStHr)){
foreach($rowStHr as $keyStHr => $valStHr){
$selectedStHr = $valStHr;
}
}
if ($valStHr == "" || $valStHr == "null"){
echo '<option value="null">--</option>';
}
else {
echo '<option value="'.$valStHr.'">' . $valStHr . '</option>';
echo '<option value="null">--</option>';
}
$sthr = 0;
while($sthr < 13){
echo '<option value="'.$sthr.'">' . $sthr . '</option>';
$sthr = $sthr++;
}
echo '</select></td></tr>';
/************* Query for Start Min *****************/
echo '<tr><td>Start Minute</td><td><select name="StartMin" id="StartMin">';
$queryStMin = mysqli_query($link, "SELECT TIME_FORMAT(StartTime, '%m') AS StartMin WHERE id = " . $id);
while ($rowStMin = mysqli_fetch_assoc($resultStMin)){
foreach($rowStMin as $keyStMin => $valStMin){
$selectedStMin = $valStMin;
}
}
if ($valStMin == "" || $valStMin == "null"){
echo '<option value="null">--</option>';
}
else{
if ($valStMin < 10){
echo '<option value="0'.$valStMin.'">0' . $valStMin . '</option>';
echo '<option value="null">--</option>';
}
else {
echo '<option value="'.$valStMin.'">' . $valStMin . '</option>';
echo '<option value="null">--</option>';
}
}
$stmin = 0;
while($stmin < 60){
if ($stmin < 10){
echo '<option value="0'.$stmin.'">0' . $stmin . '</option>';
}
else {
echo '<option value="'.$stmin.'">' . $stmin . '</option>';
}
$stmin = $stmin +5;
}
echo '</select></td></tr>';
/************* Query for Start AMPM ****************/
echo '<tr><td>Start AM/PM</td><td><select name="StAP" id="StAP">';
$queryStAP = mysqli_query($link, "SELECT TIME_FORMAT(StartTime, '%p') AS StAP WHERE id = " . $id);
while ($rowStAP = mysqli_fetch_assoc($resultStAP)){
foreach($rowStAP as $keyStAP => $valStAP){
$selected = $valStAP;
}
}
if ($valStAP != ""){
echo '<option selected name="StAP" value="' . $valStAP . '">' . $valStAP . '</option>';
}
echo '<option value="--">--</option>';
echo '<option value="am">am</option>';
echo '<option value="pm">pm</option>';
echo '</select></td></tr>';
/************* Query for End Date *****************/
$queryEndDt = mysqli_query($link, "SELECT EndDate FROM events WHERE id = " . $id);
while($rowEndDt = mysqli_fetch_assoc($queryEndDt)){
foreach($rowEndDt as $keyDesc => $valEndDt){
echo '<tr><td>Start Date: </td><td><input type="text" id="StartDate" name="StartDate" value="' . $valEndDt . '"></td></tr>';
}
}
/************* Query for End Hour *****************/
echo '<tr><td>End Hour</td><td><select name="EndHour" id="EndHour">';
$queryEndHr = mysqli_query($link, "SELECT TIME_FORMAT(EndTime, '%h') AS EndHour WHERE id = " . $id);
while ($rowEndHr = mysqli_fetch_assoc($resultEndHr)){
foreach($rowEndHr as $keyEndHr => $valEndHr){
$selectedEndHr = $valSEndHr;
}
}
if ($valEndHr == "" || $valEndHr == "null"){
echo '<option value="null">--</option>';
}
else {
echo '<option value="'.$valEndHr.'">' . $valEndHr . '</option>';
echo '<option value="null">--</option>';
}
$endmin = 0;
while($endmin < 13){
echo '<option value="'.$endmin.'">' . $endmin . '</option>';
$endmin = $endmin++;
}
echo '</select></td></tr>';
/************* Query for End Min ******************/
echo '<tr><td>Start Minute</td><td><select name="EndMin" id="EndMin">';
$queryEndMin = mysqli_query($link, "SELECT TIME_FORMAT(EndTime, '%m') AS EndMin WHERE id = " . $id);
while ($rowEndMin = mysqli_fetch_assoc($resultEndMin)){
foreach($rowEndMin as $keyEndMin => $valEndMin){
$selectedEndMin = $valEndMin;
}
}
if ($valEndMin == "" || $valEndMin == "null"){
echo '<option value="null">--</option>';
}
else{
if ($valEndMin < 10){
echo '<option value="0'.$valEndMin.'">0' . $valEndMin . '</option>';
echo '<option value="null">--</option>';
}
else {
echo '<option value="'.$valEndMin.'">' . $valEndMin . '</option>';
echo '<option value="null">--</option>';
}
}
$endmin = 0;
while($endmin < 60){
if ($endmin < 10){
echo '<option value="0'.$endmin.'">0' . $endmin . '</option>';
}
else {
echo '<option value="'.$endmin.'">' . $endmin . '</option>';
}
$endmin = $endmin +5;
}
echo '</select></td></tr>';
/************* Query for End AMPM *****************/
echo '<tr><td>End AM/PM</td><td><select name="EndAP" id="EndAP">';
$queryStAP = mysqli_query($link, "SELECT TIME_FORMAT(StartTime, '%p') AS EndAP WHERE id = " . $id);
while ($rowEndAP = mysqli_fetch_assoc($resultEndAP)){
foreach($rowEndAP as $keyEndAP => $valEndAP){
$selected = $valEndAP;
}
}
if ($valEndAP != ""){
echo '<option selected name="StAP" value="' . $valEndAP . '">' . $valEndAP . '</option>';
}
echo '<option name="EndAP" value="--">--</option>';
echo '<option name="EndAP" value="am">am</option>';
echo '<option name="EndAP" value="pm">pm</option>';
echo '</select></td></tr>';
/*************/
echo '</div>';
/************/
/************* Query for Place ********************/
$queryPlace = mysqli_query($link, "SELECT Place FROM events WHERE id = " . $id);
while($rowPlace = mysqli_fetch_assoc($queryPlace)){
foreach($rowPlace as $keyPlace => $valPlace){
echo '<tr><td>Place: </td><td><input type="text" id="Place" name="Place" value="' . $valPlace . '"></td></tr>';
}
}
/************** Query for Category *****************/
echo '<tr><td>Category</td><td><select name="category" id="category">';
$query2 = "SELECT Category FROM events WHERE id = " . $id;
$result2 = mysqli_query($link, $query2);
while ($row2 = mysqli_fetch_assoc($result2)){
foreach($row2 as $key2 => $val2){
$selected = $val2;
}
}
echo '<option name="none" value="">none</option>';
$queryCategory = "SELECT name FROM categories";
$result = mysqli_query($link, $queryCategory);
while($row1 = mysqli_fetch_assoc($result)){
foreach($row1 as $key1 => $val1){
if ($val1 != ""){
if ($val1 == $val2){
echo '<option selected name="' . $key . '" value="' . $val1 . '">' . $val1 . '</option>';
}
else {
echo '<option name="' . $key . '" value="' . $val1 . '">' . $val1 . '</option>';
}
}
}
}
echo '</select></td></tr>';
echo '<input type="hidden" name="id" value="' . $id . '" />';
echo '<tr><td><input type="submit" value="Save Changes" /></td></tr>';
echo "</table>";
echo "</form>";
This isn't a complete answer, but I'd recommend you have a look at this and revise your code. You're running unnecessary queries and there is a security error too.
//This needs to be casted here (assuming it is an int)
$id = (int) $_POST['id'];
/* Edit Event Form */
echo '<form action="edit-event-process.php" method="post">';
echo '<center><table style="text-align:center">';
/* Don't do queries individually */
$queryEvent = mysqli_query($link, "SELECT Name,Description,StartDate,AllDay FROM events WHERE id = " . $id);
if($row = mysqli_fetch_assoc($queryEvent)){
?>
<tr>
<td>Name: </td>
<td><input type="text" id="Name" name="Name" value="<?php echo $row['Name']; ?>"></td>
</tr>
<tr>
<td>Description: </td>
<td><input type="text" id="Description" name="Description" value="<?php echo $row['Description']; ?>"></td>
</tr>
<tr>
<td>Start Date: </td>
<td><input type="text" id="StartDate" name="StartDate" value="<?php echo $row['StartDate']; ?>"></td>
</tr>
<tr>
<td>All Day? </td>
<td><input type="checkbox" id="AllDay" name="AllDay"<?php if($row['AllDay'] == '1') echo 'checked="checked"'; ?>></td></tr>';
</tr>
<?php
}

Check Checkbox depending on value in database

I have an code that gets the 'branches' from the database. Each company can have multiple 'branches'.
Only thing is, that is doesn't work. Can you guys figure out what's wrong?
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);
while($rijbranche = mysql_fetch_assoc($querygetbranches))
{
echo "<tr>";
echo "<td width='400'>";
echo $rijbranche['naam'];
echo "</td>";
echo "<td>";
$get2 = "SELECT * FROM bedrijf_branche WHERE bedrijf_id = '$id'";
$query2 = mysql_query($get2);
while ($rij20 = mysql_fetch_assoc($query2))
{
$branche_id = $rij20['branche_id'];
}
if($branche_id == $rijbranche['id_branche']){
?>
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" CHECKED></input>
<?php
}
else
{
?>
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>"></input>
<?php
}
echo "</td>";
}
Try the following code
<?php
$id = $_GET['id'];
// Output BRANCHES
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);
while ($rijbranche = mysql_fetch_array($querygetbranches)) {
echo ' <tr>' . "\n";
echo ' <td width="400">' . $rijbranche['naam'] . '</td>' . "\n";
// Output CHECKBOX
$get2 = mysql_query("SELECT * FROM bedrijf_branche WHERE bedrijf_id = '" . $id . "' AND branche_id = '" . $rijbranche['id_branche'] . "'");
$rij20 = mysql_fetch_array($get2);
$branche_id = $rij20['branche_id'];
if ($branche_id == $rijbranche['id_branche']) {
$checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" checked="checked" />';
}
else {
$checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" />';
}
echo ' <td>' . $checkbox . '</td>' . "\n";
echo ' </tr>' . "\n";
}
?>
Found a couple of errors I fixed in the above code.
You're closing the <input> fields incorrectly
Your second while() loop is unnecessary as there should only be one row returned
You have to add branche_id to your second mysql_query!
Don't close and re-open your <?php ?> tags for every HTML line when you can just add an echo
Your HTML-syntax is wrong.
The way you close the input tag and the way you want to check the chechbox is wrong
Try this
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" checked="checked" />

Categories