update quantity of input box specific to each id using session array - php

I am making a shopping cart using arrays and sessions.
I would like to update the quantity of an item that has a specific id number, without updating the other quantities which have different id number.
My code is bellow and to run it, you must get id from URL.
So just put ?id=1 in front of the .php in the address bar (as I am sure everyone is aware of more than me).
Cart.php
<?php
session_start();
// set the array and store in session
$_SESSION['items'][]=array(
'id'=>"'".$_GET['id']."'",
'qty'=> 1
);
// Display each array value stored in the session
foreach ($_SESSION['items'] as $value) {
// Display the id
echo 'The ID is ' ."''''" . $value['id'] ."''''" ;
// Display the Qty
echo 'the QTY ' ."''''" . $value['qty'] ."''''" ;
echo "<br/>";
//Echo a form that displays the Qty in a input box,
// My problem is that, I cant update the qty value in the input box where each id is different.
echo "<form method='post' action='id.php' name='edit'>
<p>Quantity: <input type=\"text\" size=\"20\" name='".$value['id']."' value='".$value['qty']."'/> </p><br>
<input class='save' name='update' value='update' type='submit'>
</form>";
}
// check if the update button is submited so that the qty value can be changed where the id number of the selected qty input box is edited
if (isset($_POST["update"])) {
$_SESSION['item'][$id]= $_POST["'".$value['id']."'"];
}
else
{
echo "quantity is updated";
}
?>

Unless you are making a $_SESSION['items'] Array of Arrays, change
$_SESSION['items'][]
to
$_SESSION['items']
Otherwise, you'll need a loop within your loop.
Right now, $value in
foreach ($_SESSION['items'] as $value) {
really represents an Array, which has your other Array in it. Additionally, you should not have more than one form with the same name. Don't put a form in a loop unless you're changing the name at each step of the loop.

Related

creating dynamic variables in php to update multiple rows in MYSQL

I am currently working on an update profile section of a website I am creating for fun. In this part of the update profile business owners can update their restaurant menu (menu consists of category (appetizers, entrees, etc), menu item and allergens).
Right now the website is printing out what the business owner has previously submitted in input box format, this way business owners can simply just erase and re-enter their new information. However, we don't know exactly how many menu items each restaurant has so I devised a system to dynamically update each item being altered row by row.
<?php
$sql="SELECT * from menu_item as m, allergen as a WHERE a.restaurant_id=m.restaurant_id AND m.menu_item_id=a.menu_item_id AND m.restaurant_id='".$rest_id."'";
$result11=mysqli_query($con,$sql);
if (mysqli_num_rows($result)==0){
echo "<strong>You have not submitted any menu information</strong><br><br>";
echo "Please enter your menu information here: ";
echo 'Create Menu';
}
else{
$i=0;
echo "<table border='1' cellpadding='10'><tr><th>Category</th><th>Menu Item</th><th>Allergen</th></tr>";
while($rows=mysqli_fetch_assoc($result11)) {
echo '<tr><td><input type="text" name="category'.$i.'"value="'. $rows['category']. '"</td><br>';
echo '<td><input type="text" name="menu_item'.$i.'" value="'. $rows['menu_item']. '"</td><br>';
echo '<td><input type="text" name="allergen'.$i.'" value="'. $rows['allergen']. '"</td><br>';
echo '<td><input type="hidden" name="id'.$i.'" value="'. $rows['menu_item_id']. '"</td></tr><br>';
$i++;
}
}
echo "</table>";
var_dump(mysqli_num_rows($result11));
// var_dump($_POST);
$count=0;
while ($count<=mysqli_num_rows($result11)){
${"category".$count}=mysqli_real_escape_string($con, $_POST['category'.'$count']);
$count++;
}
var_dump($category0);
?>
This is where the while loop near the bottom comes into play. I want to be able to dynamically create variables for category, menu item, and allergen. Then I want to be able to create $result variables within this same while loop (mysqli_query) and then update rows accordingly. However, right now my very last var_dump is returning a value of "" which tells me I'm either concatenating the html name attribute wrong(first while loop) or there is something wrong with concatenation in my last while loop. Does anyone know what I'm doing wrong?
$_POST['category'.'$count'] in your second loop should be $_POST['category'.$count]. You also only want to run this code after the form has been submitted (I'm assuming the code you've posted is not your full script so it's not clear if that's what is happening) - otherwise you'll get the original values rather than any changes the user has made in the form.
In general you'll have an easier time if you can get the submitted data into a multi-dimensional array which you can loop through, instead of having to dynamically create variables. See the section "How do I create arrays in a HTML form?" on http://php.net/manual/en/faq.html.php. In your case I'd do something like:
// (in your first while loop)
echo '<input type="text" name="menu['.$i.'][category]" value="'. htmlspecialchars($rows['category']). '"><br>';
echo '<input type="text" name="menu['.$i.'][menu_item]" value="'. htmlspecialchars($rows['menu_item']). '"><br>';
// (etc.)
You then loop through this with something like:
foreach ($_POST['menu'] as $menuRow) {
// you now have:
// $menuRow['category']
// $menuRow['menu_item']
// ...and so on
}
You also want to escape the input values you are outputting with htmlspecialchars() as I have above.

update cart with php sessions

I am trying to update my cart quantity,my products are displayed with foreach loop .So, I tried to update it through this code , it worked but only for the first item selected on addtocart submit . What is the problem ? how to make the update for each item on one update button click ?
if (isset($_POST["quansub"]) ){
$itq = $_POST["itq"];
$_SESSION["itq"] = $itq;
$_SESSION["incart"][$select]["item_quantity"]= $_SESSION["itq"];
header("location:selecteditems.php");
}
Is this the sort of thing you want?
I would suggest for each item in your cart have something like this:
<input type='hidden' name='quantity[1]' id='quantity[1]'>
<input type='hidden' name='quantity[2]' id='quantity[2]'>
foreach($_POST['item'] AS $key=>$value){
$qty = $_POST["quantity"][$key];
$_SESSION["quantity"][$key] = $qty;
$_SESSION["incart"][$select]["item_quantity"]= $_SESSION["quantity"][$key];
}
Where you have "$select", use it to do the following:
<input type="text" name="itq[<?= $select ?>]" value="<?php echo $val["item_quantity"]; ?>"/>
Then do the following in PHP:
if (isset($_POST["quansub"] && $_POST['itq'][$select])){
$_SESSION["incart"][$select]["item_quantity"] = $_POST["itq"][$select];
}
Move this code outside of the foreach loop:
if (isset($_POST["quansub"])){
header("location:selecteditems.php");
}
Having "quantity[1], quantity[2]" etc... makes it very easy to loop through the input values and get out their values. This is very useful when storing multiple items into a database that are using the same names.
Giving the names a unique "key" also means you can determine where they belong to in a database as well as you could give them the "key" by using their database or product id for example.
If you want me to explain individual parts to this let me know.

PHP Session Variables - passing through pages

Im hoping someone can point me in the right direction of where im going wrong as I feel like im going around in circles!
Im putting together a simple shopping applications - its only very basic at the moment to demonstrate techniques.
The scenario is that there is one database table with items in. They have been split into a blue and red range of items.
On the index page the user has the option of going to either the blue or red items.
Once on the red (or blue) items page, items are displayed and current price and stock level is pulled from the database (MySQL). The user then selects one item and clicks the buy button to add it into their cart.
The page then redirects to the shopping cart page where the user can either update the quantity of the item, proceed to the checkout page or return to the 'red' or 'blue' ranges.
My issue is this.....
1) How do I set up my session array to capture the items as they are added on the buy 'click'?
So far I have this on the top of all pages...
<?php session_start();
?>
However only one item seems to be able to be added to the 'cart'.
This is how im pulling items from my DB:
<?php
$result = mysql_query ('SELECT * FROM items WHERE colour="red"');
// fetch the resulting row as an associative array
while ($row = mysql_fetch_assoc ($result)){
echo '£', number_format( $row ['price'] / 100, 2, '.', ' ' );
}
?></p>
2) This is the code for the form action under each item on either the red or blue page.
<form method="post" action="cart.php">
<p>
<input type="submit" name="submit" value="Buy" />
<input type="hidden" name="cart" value="add" />
<input type="hidden" name="item" value="redplate" />
</p>
</form>
3) How do I display the 'ordered' item in the checkout page after any quantity updates on the shopping cart page?
So far this is what it on the shopping cart page - would I repeat this on the checkout page pulling with it the updated quantity??....
<?php
$submit = $_POST["submit"];
//Call the function and save all data into the array $_SESSION['form']
if($submit == "Buy"){setSessionVars();}
function setSessionVars() {
$item = array();
foreach($_POST as $fieldname => $fieldvalue) {
$item[$fieldname] = $fieldvalue;
}
$_SESSION['cart'] = $item;
echo " <table>
<tr>
<td>
<img src=\"images/{$item['item']}.jpg\" />
<td/>
<td>
{$item['item']} =
</td>
<td>
<input type=\"text(5)\" name=\"value\" value=\"1\" />
<input type=\"submit\" name=\"puchasedquan\" value=\"Click to update\" />
</td>
</tr>
</table>";
}
?>
Any help would be greatly appreciated!! I feel as if i'm traveling around in circles!
The problem with storing things in the PHP session vars is that they are stored in cookies, that means they require cookies to be turned on. Okay, most browsers have cookies set nowadays.
But how about if you read values directly from a client file, and put that into your database? Whats to stop someone from hacking the cookie file where it says "subtotal=10000" and changing the value to "subtotal=1", then push that through your system?
Your system would be more robust if you actually store the shopping session in your database, e.g.
CREATE TABLE tbl_shopping_session(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
php_session_key VARCHAR(32),
coupon_id INT,
FOREIGN KEY(coupon_id) REFERENCES tbl_coupons(id),
updated TIMESTAMP /* a timestamp is added to find & del old sessions */
) ENGINE = InnoDB;
CREATE TABLE tbl_shopping_cart(
shopping_session_id INT,
FOREIGN KEY(shopping_session_id) REFERENCES tbl_shopping_session(id) ON DELETE CASCADE,
product_id INT,
FOREIGN KEY(product_id) REFERENCES tbl_products(id),
cart_qty INT /* or DECIMAL(9,3) or something */,
subtotal DECIMAL(18,4)
) ENGINE = InnoDB;
From there on you could get the picture... the php_session_key is used to identify the current shopping session, and the current session id is used to find & store the cart items in a separate table.
The big mistake here is, you are putting all you datas on one session variable altogether, i.e. $_SESSION['cart'].
Since you want to insert multiple item on the sessions, you have use $_SESSION['cart'][] to insert the items.
Whenever you are trying to get the values stored, again use a for loop to read as well as .
foreach($_SESSION['cart'] as $cartItem) {
$cartItem; // will have all the item individually on each pass
}
try this
$item = array();
foreach($_POST as $fieldname => $fieldvalue) {
$item[$fieldname][] = $fieldvalue;
}
The $_SESSION keys are being replaced when you add more, so really it's just overwriting an existing value, you could add this:
foreach($_POST as $fieldname => $fieldvalue) {
// Now the array will be enumerated
$item[$fieldname][] = $fieldvalue;
}
print_r($item);

Input Type Hidden Fields in a foreach loop

I'm trying to add submit buttons and hidden input fields so that when a user clicks a submit button I can identify the item they selected. Although I can't figure out how to access the hidden values. I have this code (the value in input type="hidden" are the item's id's). How do I access the values?
foreach($dbh->query("SELECT * FROM beer WHERE country_id = $countryID") as $beer) {
echo "<a href='BeerSummary.php?beerID=$beer[id]'>$beer[2]</a> <br/>";
echo "ABV $beer[3]% - $beer[4] ml - Case Size $beer[5] - Price £$beer[6]";
echo '<input type="submit" value="Add to Cart"> <br/>';
echo '<input type="hidden" name="beer_id[]" value="'.$beer[0].'">';
echo "<br/>";
}
if(isset($_POST["beer_id"])) {
//
}
You have them defined as an input array, so the way to access it/them would be:
foreach($_POST['beer_id'] as $value)
{
echo $value;
}
for each of hidden fields, take id. id = hidden + $beer[i]
then u can easily access the hidden fields with document.getElementById("hidden" + $beer[i])
this will work in javascript.
if u want to so the same in php, #Ben's answer should work.

Replace html button value with php and store it in database?

//Following code to generate 25
Button with unique name for each
button
// 25 buttons contains value
from 1 to 25
// like
btn1='1',btn2='2' ... btn25='25'
<?php
$j=0;
for($i=1;$i<=25;$i++)
{
$j++;
?>
<td><input type='button' id='btn' name="btn<?php echo $i;?>" value='<?php echo $i;?>' onclick="cnt(btn<?php echo $i;?>);" ></td>
<?php
if($j==5)
{
echo "</tr>";
echo "<tr>";
$j=0;
}
}
?>
// and using concantation i'm inserting button values seqhence into database
// like user will click on first 5 button i will insert seq=1-2-3-4-5 which are html button values
// and then using php insert query i'm inserting the sequene in db
// concantation code i'm not given here
$con="INSERT INTO `vector`.`signup` (`userid` ,`seq`)VALUES ('".$usr."', '".$seq."')";
mysql_query($con) or die ('Bad Input');
?>
see this databse picture
http://i53.tinypic.com/1zudjo.jpg
Now my prb is i want to store different values in database .. for each buton
like btn1='1' has value 1 when user will click i want to store diffvalue like 'a1' . which should not
available to user on client side .. i want to do with php ..
how can i change html button value with php code to store in databse...
i want btn1='1' to be btn1='a1' in database..
$databasevalue = 'a' . $_POST['btn1'];
Seems rather obvious... just prepend whatever you want to the value coming out of the form.

Categories