Storing multiple items into a session - php

I am trying to store multiple items into a session. I am posting an items from a form like so:
<?php
$product_id = $_GET['product_id'];
$sql = "SELECT * FROM Products WHERE product_id = $product_id";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<img src=' . $row['product_img'] . ' />';
echo '<div class="title">'. $row['product_name'] .'</div>';
echo '<div class="title">'. $row['product_price'] .'</div>';
echo '<div class="title">'. $row['product_sku'] .'</div>';
echo '<div class="title">'. $row['product_description'] .'</div>';
echo '<form action="addToCart.php" method="post">
<input type="hidden" name="product_img" value="' . $row['product_img'] . '" />
<input type="hidden" name="product_id" value="' . $row['product_id'] . '" />
<input type="hidden" name="product_name" value="' . $row['product_name'] . '" />
<input type="hidden" name="product_price" value="' . $row['product_price'] . '" />
<input type="hidden" name="product_sku" value="' . $row['product_sku'] . '" />
<input type="hidden" name="product_description" value="' . $row['product_description'] . '" />
<input type="submit" name="Submit">
</form>';
}
} else{
echo "0 Results";
}
?>
addToCart.php looks like this:
<?php
if (isset($_POST['Submit'])) {
$_SESSION['product_img'] = $_POST['product_img'];
$_SESSION['product_id'] = $_POST['product_id'];
$_SESSION['product_name'] = $_POST['product_name'];
$_SESSION['product_price'] = $_POST['product_price'];
$_SESSION['product_sku'] = $_POST['product_sku'];
$_SESSION['product_description'] = $_POST['product_description'];
}
?>
So the above is now setting the items into the session (So I believe). I am then outputting the item from the stored data in basket.php
<?php echo '<img src=' . $_SESSION['product_img'] . ' />'; ?>
<?php echo $_SESSION['product_id'];?>
<?php echo $_SESSION['product_name'];?>
<?php echo $_SESSION['product_price'] ?>
<?php echo $_SESSION['product_sku']; ?>
<?php echo $_SESSION['product_description']; ?>
the Issue I have is whenever I add another item it overrides the previous item? I know I need to use an array to store multiple items but I have tried a few different things but I am struggling to understand.

You can use [] to store them in array:
$_SESSION['product_img'][] = $_POST['product_img'];
$_SESSION['product_id'][] = $_POST['product_id'];
$_SESSION['product_name'][] = $_POST['product_name'];
$_SESSION['product_price'][] = $_POST['product_price'];
$_SESSION['product_sku'][] = $_POST['product_sku'];
$_SESSION['product_description'][] = $_POST['product_description']
Now, try to see what are in each array:
var_dump($_SESSION['product_id']);

It is possible to store your Session Data as nested array. In your case, since it is a Shopping Cart, you may want to build your Arrays using the ID of the Product; that way you are certain that no product will override the other (so long as they don't have the same product_id values.... Below is an example of how you may do that:
<?php
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
if (isset($_POST['Submit'])) {
$product_id = htmlspecialchars(trim($_POST['product_id']));
$product_img = htmlspecialchars(trim($_POST['product_img']));
$product_sku = htmlspecialchars(trim($_POST['product_sku']));
$product_name = htmlspecialchars(trim($_POST['product_name']));
$product_price = htmlspecialchars(trim($_POST['product_price']));
$product_description = htmlspecialchars(trim($_POST['product_description']));
if(!isset($_SESSION['products'])){
$_SESSION['products'] = array();
}
if(!isset($_SESSION['products'][$product_id])){
$_SESSION['products'][$product_id] = array();
}
$_SESSION['products'][$product_id]['product_id'] = $product_id;
$_SESSION['products'][$product_id]['product_img'] = $ $product_img;
$_SESSION['products'][$product_id]['product_name'] = $product_name;
$_SESSION['products'][$product_id]['product_price'] = $product_price;
$_SESSION['products'][$product_id]['product_sku'] = $product_sku;
$_SESSION['products'][$product_id]['product_description'] = $product_description;
}
And anywhere else (another Script perhaps) you could access your Data like so:
<?php
$output = "";
$storedProductData = $_SESSION['products'];
if(!empty($storedProductData)){
foreach($storedProductData as $product_id=>$productData){
$output .= "<img src='{$productData['product_img']}' />" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_id']}</span>" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_name']}</span>" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_price']}</span>" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_sku']}</span>" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_description']}</span>" . PHP_EOL;
}
}

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';
?>

Unsetting an item from an array in a session

I am trying to remove an item from my array in a stored session. I have attempted the following but it reverses and actually adds more!
So here is my foreach where the product shows in the cart with a button to remove from the cart:
foreach ($_SESSION['products'] as $product) {
$name = $product['name'];
$id = $product['id'];
$price = $product['price'];
$img = $product['img'];
$sku = $product['sku'];
$description = $product['description'];
echo '<a href="single_product.php?product_id=' . $product['products'] . '">';
echo "<img src='$img'><br />";
echo "Product: $name<br />";
echo "Price: $price | ID: $id<br />";
echo "$description";
echo '</a><br /><br />';
echo '<form action="removeItem.php" method="post">
<input type="hidden" name="product_id" value="' . $product['id'] . '" />
<button name="removeItem">Remove</button>
</form>';
$sum += $price;
}
And here is the form to remove it but it actually adds more when you hit remove:
$_SESSION['products'][] = $itemid;
$id = $_POST['id'];
unset($_SESSION['products'][$id]);
header("location:basket.php");
Try something like this:
$product_id = $_POST["id"];
foreach($_SESSION['products'] as $key=>$product) {
if($product['id'] == $product_id) {
unset($_SESSION['products'][$key]);
break;
}
}

Invalid argument supplied for foreach() - Yet output is showing

I am working to show editable fields based on query results. I know the query is functioning properly, and it is returning an array. The array is populating the form fields properly, however, I am getting the "Invalid argument supplied for foreach()" warning. I am new at this, and at a loss as to what is happening. I appreciate any suggestions.
Here is the code:
// Grab the profile data from the database
$query8 = "SELECT * FROM EDUCATION WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' ORDER BY RECORD";
$data = mysqli_query($dbc, $query8);
echo '<pre>' . print_r($data, true) . '</pre>';
$rowcount = 1;
while ($row = mysqli_fetch_assoc($data))
{
if (is_array($row))
{
echo '<p> It is an Array</p>';
}
foreach($row as &$item)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Education History </legend>
<?php
echo '<input type="hidden" id="record" name="record" value="' . $record . '">';
echo 'Rowcount' . $rowcount. '</br>';
// Insert Listbox here
$queryschool = "SELECT * FROM SCHOOL";
$list = mysqli_query($dbc, $queryschool);
if($list)
{
echo 'School Type? ';
echo '<select name="school_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['TYPE']}" ;
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="school">School Name:</label>';
echo '<input type="text" id="school" name="school" size="40" maxlength="40" value="' . ( (!empty($school)) ? $school : "") . '" /><br />';
// Insert Listbox here
$querydegree = "SELECT * FROM DEGREE";
$list = mysqli_query($dbc, $querydegree);
if($list)
{
echo 'Degree Type? ';
echo '<select name="degree_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['DEGREE']}";
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="major">Field of study:</label>';
echo '<input type="text" id="major" name="major" size="40" maxlength="40" value="' . ( (!empty($major)) ? $major : "") . '" /><br />';
echo '<label for="grad">Did you graduate?:</label>';
echo '<input type="radio" id="grad" name="grad" value="Y" ' . ($grad == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="grad" name="grad" value="N" ' . ($grad == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
</fieldset>
<?php
$rowcount++;
}
}
;
echo '<label for="another">Do you need to enter more educational experience?:</label>';
echo '<input type="radio" id="another" name="another" value="Y" ' . ($another == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="another" name="another" value="N" ' . ($another == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
<input type="submit" value="Save Profile" name="submit" />
</form>
foreach ($row as &$item)
replace this with:
foreach ($row as $item)
And then for each variable you should probably change
$record = $row['RECORD'];
to
$record = $item['RECORD'];
foreach($row as &$item) should be
foreach($row as $item)
there is no need to use the foreach here you can just do this like like
while ($row = mysqli_fetch_assoc($data))
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
}
You're not changing the row item, so don't pass by reference to the foreach. Also, shouldn't you be using $item instead of $row? Do this:
foreach($row as $item)
{
$record = $item['RECORD'];
$school = $item['SCHOOL'];
....
Don't do This:
foreach($row as &$item)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
....

WIll foreach loop accomplish this? How?

I am trying to create a form page that will allow the end-user the ability to update multiple entries in a table. The user is tagged by an ID_NUM and the entries by RECORD. I want to display each row in the form, with each row stacked on the page in separate instances. As below:
School Name:
School Type:
Degree:
Major:
Graduate:
School Name:
School Type:
Degree:
Major:
Graduate:
I want the submit to trigger an update to any changes in any row. Here is the code I have for the basic form. What do I need to do to integrate the foreach loop, if that is the best way to solve the problem?
<?php
// Start the session
require_once('startsession.php');
// Insert Page Header
$page_title = 'Edit Profile';
require_once('header.php');
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['email'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
// Insert navmenu
require_once('navmenu.php');
require_once('vary.php');
require_once('appvars.php');
require_once('connectvars.php');
// Connect to the database using vary.php
if (isset($_POST['submit']))
{
// Grab the profile data from the POST
$record2 = $_POST['record'];
$school2 = $_POST['school'];
$type2 = $_POST['school_code'];
$degree2 = $_POST['degree_code'];
$desc2 = $_POST['desc'];
$grad2 = $_POST['grad'];
$another2 = $_POST['another'];
// Update the profile data in the database
if (!empty($school2)) {
$query3 = "UPDATE EDUCATION SET SCHOOL = '$school2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 . "'";
mysqli_query($dbc, $query3);
}
if (!empty($type2)) {
$query4 = "UPDATE EDUCATION SET TYPE = '$type2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 . "'";
mysqli_query($dbc, $query4);
}
if (!empty($degree2)) {
$query5 = "UPDATE EDUCATION SET DEGREE = '$degree2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 . "'";
mysqli_query($dbc, $query5);
}
if (!empty($desc2)) {
$query6 = "UPDATE EDUCATION SET MAJOR = '$desc2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 . "'";
mysqli_query($dbc, $query6);
}
if (!empty($grad2)) {
$query7 = "UPDATE EDUCATION SET GRAD = '$grad2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 ."'";
mysqli_query($dbc, $query7);
}
// Confirm success with the user
if ($another2=="Y")
{
// Clear the variables and reload the page for new submit
$record2 = "";
$school2 = "";
$type2 = "";
$degree2 = "";
$major2 = "";
$grad2 = "";
$another2 = "";
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.avant.jobs/portal/addeducation.php">';
}
else
{
echo '<p>The education section of your profile has been successfully updated. Would you like to continue??</p>';
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.avant.jobs/portal/workcheck.php">';
}
mysqli_close($dbc);
exit();
}
else
{
echo '<p class="error">You must enter all of the profile data.</p>';
}
// End of check for form submission
// Grab the profile data from the database
$query8 = "SELECT * FROM EDUCATION WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "'";
$data = mysqli_query($dbc, $query8);
$row = mysqli_fetch_array($data);
if ($row != NULL)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$desc = $row['MAJOR'];
$grad = $row['GRAD'];
}
else
{
echo '<p class="error">There was a problem accessing your profile.</p>';
}
;
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Education History </legend>
<?php
echo '<input type="hidden" id="record" name="record" value="' . $record . '">';
// Insert Listbox here
$queryschool = "SELECT * FROM SCHOOL";
$list = mysqli_query($dbc, $queryschool);
if($list)
{
echo 'School Type? ';
echo '<select name="school_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['TYPE']}" ;
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="school">School Name:</label>';
echo '<input type="text" id="school" name="school" size="40" maxlength="40" value="' . ((!empty($school)) ? $school : "") . '" /><br />';
// Insert Listbox here
$querydegree = "SELECT * FROM DEGREE";
$list = mysqli_query($dbc, $querydegree);
if($list)
{
echo 'Degree Type? ';
echo '<select name="degree_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['DEGREE']}";
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="desc">Field of study:</label>';
echo '<input type="text" id="desc" name="desc" size="40" maxlength="40" value="' . ( (!empty($desc)) ? $desc : "") . '" /><br />';
echo '<label for="grad">Did you graduate?:</label>';
echo '<input type="radio" id="grad" name="grad" value="Y" ' . ($grad == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="grad" name="grad" value="N" ' . ($grad == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
</fieldset>
<?php
echo '<label for="another">Do you need to enter more educational experience?:</label>';
echo '<input type="radio" id="another" name="another" value="Y" ' . ($another == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="another" name="another" value="N" ' . ($another == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
<input type="submit" value="Save Profile" name="submit" />
</form>
<?php
// Insert Page Footer
require_once('footer.php');
?>
As I am new to this and trying to teach my self, any help is appreciated! Thank you.
Instead of having multiple UPDATE queries, you can integrate them to 1 query,
$comma = FALSE;
$query = "UPDATE EDUCATION SET ";
// Update the profile data in the database
if (!empty($school2)) {
$query .= "SCHOOL = '$school2'";
$comma = TRUE;
}
if (!empty($type2)) {
if($comma === TRUE)
$query .= ", ";
$query .= "TYPE = '$type2' ";
$comma = TRUE;
}
if (!empty($degree2)) {
if($comma === TRUE)
$query .= ", ";
$query5 = "DEGREE = '$degree2'";
$comma = TRUE;
}
if (!empty($desc2)) {
if($comma === TRUE)
$query .= ", ";
$query .= "MAJOR = '$desc2'";
$comma = TRUE;
}
if (!empty($grad2)) {
if($comma === TRUE)
$query .= ", ";
$query .= "GRAD = '$grad2'";
}
$query .= "WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 ."'";
if (!empty($school2) || !empty($type2) || !empty($degree2) || !empty($desc2) || !empty($grad2)) {
mysqli_query($dbc, $query);

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