Update cart - mysql table update - while loop - php

new guy here!
I am building a custom shopping cart driven by mysql and i am trying to update my cart item by item in terms of quantity. It seems that i am doing something wrong because when i try to update the quantity it only update the last item. I am posting the code below. Any help would be appreciated. Thanks in advance.
1.cart.php:
$sql = "select * from orders";
$result = mysql_query($sql);
$num = mysql_num_rows($result);
echo "Στοιχεία: ".$num;
?>
<form name="cart" method="post" action="updatecart.php">
<table border="2">
<tr>
<td>Α/Α</td>
<td>img_name</td>
<td>Reprints</td>
<td>Color</td>
</tr>
<?php
if($num){
while ($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row['item_id']; ?></td>
<td><?php echo $row['img_name']; ?></td>
<td><input type="number" name="quantity" value="<?php echo $row['quantity']; ?>"></td>
<input type="hidden" name="item_id" value="<? echo $row['item_id']; ?>">
<td><?php echo $row['color']; ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="update" value="Update Cart" />
<input type="button" name="2checkout" value="Proceed to Checkout" />
</form>
2.updatecart.php
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<?php
$database_name = "vog";
$conn = mysql_connect("localhost","root","toor");
mysql_select_db($database_name);
$num = 2; //na to ferw me session meta edw!
if(isset($_POST['update'])){
$item_id = $_POST['item_id'];
$i=1;
while($i<=$num){
$item_id = $_POST['item_id'][$i];
$quantity = $_POST['quantity'];
$sql2 = "update orders SET quantity = '$quantity' where item_id = '$item_id' ";
$result2 = mysql_query($sql2) or die ("Error in query: $result2");
$i++;
}
}
if(isset($result2)){
header("Location:cart.php");
}
?>
So far it updates just the last record.

Your problem is with the names of the fields in your HTML form:
<input type="number" name="quantity" value="<?php echo $row['quantity']; ?>">
<input type="hidden" name="item_id" value="<? echo $row['item_id']; ?>">
I think you meant to call them quantity[] and item_id[] instead, so they will and up as arrays in your $_POST variable later on, now they overwrite eachother, making $_POST['item_id'] only contain the last id in the database.

in #1.cart.php use the inputs as array:
<input type="number" name="quantity[<?php echo $row['item_id']; ?>]" value="<?php echo $row['quantity']; ?>">
<input type="hidden" name="item_id[<?php echo $row['item_id']; ?>]" value="<? echo $row['item_id']; ?>">
and in #2.updatecart.php: process it like
foreach($_POST['item_id'] as $key => $id){
$item_id = $id;
$quantity = $_POST['quantity'][$key];
$sql2 = "update orders SET quantity = '$quantity' where item_id = '$item_id' ";
$result2 = mysql_query($sql2) or die ("Error in query: $result2");
$i++;
}

You need to tell PHP that you're using an array for your submitted form items. The way to do this is to make the name of each input quantity[]. You can also place the item ID directly in the array as a key. In cart.php you can do this in your loop:
<input type="number" name="quantity[<?php echo $row['item_id']; ?>]"
value="<?php echo $row['quantity']; ?>"/>
In effect, this will putput something like:
<input type="number" name="quantity[2]" value="1" />
<input type="number" name="quantity[4]" value="1" />
<input type="number" name="quantity[8]" value="2" />
i.e. 1 of item 2, 1 of item 4 and 2 of item 8.
Then, in updatecart.php you can read in the array and process it in a loop.
if(isset($_POST['update'])){
foreach ($_POST['quantity'] as $item_id => $item_qty) {
$item_id = (int)$item_id;
$item_qty = (int)$item_qty;
$sql2 = "update orders SET quantity = '$item_qty' where item_id = '$item_id' ";
mysql_query($sql2);
}
}

Related

How to get ID on a specific row in PHP and MySQL

PHP is giving me error of
Notice: Undefined index: product_id in C:\xampp\htdocs\odieinventory\admin\add_sales.php on line 6
This is my query
<?php
if (isset($_POST['addCart'])) {
$product_id = $_POST['product_id'];
$qtyBuy = $_POST['qtyBuy'];
$addQuery = "INSERT INTO sales (product_id, quantity) VALUES ($product_id, $qtyBuy)";
$execQuery = mysqli_query($connection, $addQuery);
}
?>
This is my table
<form action="add_sales.php" method="POST">
<?php
$query = "SELECT * FROM products";
$exec = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($exec)) {
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$description = $row['description'];
$product_quantity = $row['quantity'];
$product_price = $row['sell_price'];
?>
<tr>
<td class="text-center"><?php echo $product_id; ?>
<input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
</td>
<td><?php echo $product_name; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $product_price; ?></td>
<td><?php echo $product_quantity; ?></td>
<td><input type="number" min="1" max="999" name="qtyBuy"></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="form-group">
<input type="submit" name="addCart" value="Add Items to Cart" class="btn btn-info pull-right">
</div>
</div>
</form>
I would also like to ask for advice on how to insert records on my cart. By clicking 'Add Items to Cart', I like to pass ONLY the items with values on the quantitiy input on the cart. How to achieve this with PHP?
In your table file table.php , you have to:
1- open the table and tbody HTML tags
2- make your html attributes form name as array (you have more than one input with the same name), in your case you are only submiting the last product_id and the last qtyBuy input values.
table.php
<form action="add_sales.php" method="POST">
<div><table><tbody>
<?php
$query = "SELECT * FROM products";
$exec = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($exec)) {
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$description = $row['description'];
$product_quantity = $row['quantity'];
$product_price = $row['sell_price'];
?>
<tr>
<td class="text-center"><?php echo $product_id; ?>
<input type="hidden" name="product_id[]" value="<?php echo $product_id; ?>">
</td>
<td><?php echo $product_name; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $product_price; ?></td>
<td><?php echo $product_quantity; ?></td>
<td><input type="number" min="1" max="999" name="qtyBuy[]"></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="form-group">
<input type="submit" name="addCart" value="Add Items to Cart" class="btn btn-info pull-right">
</div>
</form>
In your add_sales.php file, you have to loop the $_POST['qtyBuy'] variable and check if the given quantity of each product is > 0
add_sales.php
<?php
if (isset($_POST['addCart']) && $_POST['addCart']=="Add Items to Cart") {
foreach($_POST['qtyBuy'] as $index=>$value){
if($value > 0){
$addQuery = "INSERT INTO sales (product_id, quantity) VALUES (".$_POST['product_id'][$index].", ".$value.")";
$execQuery = mysqli_query($connection, $addQuery);
}
}
}
?>
First of all, you should never put users input ($_POST) directly into the SQL to avoid SQL injection - use prepared statements with mysqli.
It would be easiest for you to add a separate form with product ID and quantity field and an "Add to cart" button for each product in the table.

PHP displaying updated values

the quantity is an array of items
<td>
<input type="text" size="4" name="qty[<?php echo $pro_id;?>]"style="text-
align:center" value="<?php echo $_SESSION['qty']; ?>">
</td>
<?php
the update function works perfectly
if(isset($_POST['update'])) {
$ip=getIp();
$sql = "UPDATE cart SET qty=? where p_id=? and ip_add=?";
$stmt = mysqli_prepare($con, $sql);
foreach ($_POST['qty'] as $pro_id=>$qty) {
$stmt->bind_param("iis", $qty, $pro_id, $ip);
$stmt->execute();
}
}
this is what i used to display the new quantity, but the values are displayed in the incorrect product field
$sql = $con->query("select * from cart where p_id='$pro_id'");
$row=$sql->fetch_array(MYSQLI_BOTH);
$_SESSION['qty']=$row['qty'];
?>
the button which updates the cart
<td><input type="submit" name="update" value="Update quantity"></td>
<td><button style="height:20px;width:128px">
Continue Shopping</button></td>
<td><button>Checkout</button>
</td>
</table>
When the quantity is a array and the data in the database is correct you need the SESSION qty as a Array!
Try this:
$sql = $con->query("select * from cart where p_id='$pro_id'");
$row=$sql->fetch_array(MYSQLI_BOTH);
$_SESSION[$pro_id]['qty']=$row['qty'];
and this
<td>
<input type="text" size="4" name="qty[<?php echo $pro_id;?>]"style="text-
align:center" value="<?php echo $_SESSION[$pro_id]['qty']; ?>">
</td>
<?php

Show data with the same name only once

I need to show my billing history, so user can automatically submit by clicking submit. But instead of showing all transactions, I only have to show for each billing_name, so I should use SELECT DISTINCT right?
<?php
$query3 = "SELECT DISTINCT billing_name, billing_reference_num FROM billing_history";
$result3 = mysqli_query($link, $query3) or die(mysqli_error($link));
while ($row3 = mysqli_fetch_array($result3)) {
$billing_name = $row3['billing_name'];
$billing_reference_num = $row3['billing_reference_num'];
?>
<td><?php echo $billing_name ?></td>
<td><?php echo $billing_reference_num ?></td>
<?php
$queryBill = "SELECT * FROM billing_history WHERE billing_name = '$billing_name'";
$resultBill = mysqli_query($link, $queryBill) or die(mysqli_error($link));
while ($row4 = mysqli_fetch_array($resultBill)) {
$billing_name_id = $row4['billing_name_id'];
$account_id = $row4['account_id'];
$account_number = $row4['account_number'];
}
?>
<td><input type="text" name="transaction_amount"/></td>
<td><input type="submit" value="Submit"/></td>
<input type="hidden" name="billing_name_id" value="<?php echo $billing_name_id ?>"/>
<input type="hidden" name="billing_name" value="<?php echo $billing_name ?>"/>
<input type="hidden" name="billing_reference_num" value="<?php echo $billing_reference_num ?>"/>
<input type="hidden" name="account_number" value="<?php echo $account_number ?>"/>
<input type="hidden" name="account_id" value="<?php echo $account_id ?>"/>

invalid argument foreach() in PHP

I have a shopping cart with a foreach() to update the quantities.
HTML
<form method="post" >
<?php while ($data2 = mysql_fetch_array( $data)) { ?>
<tr>
<td> <input name="quantity" type="text" class="form-field" size="3" value="<? echo $data2['quantity'];?>" />
<input type="hidden" name="product_id" value="<? echo $data2['product_id']; ?>">
</td>
</tr>
<? } ?>
</form>
AND FOR MY PHP, I have
if (isset($_POST['submit_qty']))
{
foreach($_POST['product_id'] as $key => $id)
{
$item_id = $id;
$quantity = $_POST['quantity'][$key];
$sql2 = "update cart SET quantity = '".$quantity."' where product_id = '".$item_id."' ";
$result2 = mysql_query($sql2) or die ("Error in query: $result2");
}
header('Location: mycart.php');
exit();
}
IF I Echo my sql query I get :
Warning: Invalid argument supplied for foreach()
what could be the problem ?
You aren't passing your product_id as an array.
Try <input type="hidden" name="product_id[]" value="<? echo $data2['product_id']; ?>">

saving data from an array without submitting any form php

I'm tryng to save an array so I have the following code:
<?php
$sql = "SELECT * FROM scenarii where code_s='".mysql_real_escape_string($_POST['code_s'])."'";
$qry = mysql_query($sql) or die(__LINE__.mysql_error().$sql);
$i = -1; // index des enregistrements
?>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>CODE SCENARIO</strong></td>
<td><strong>LIBELLE</strong></td>
<td><strong>ACTION</strong></td>
<td><strong>DESCRIPTION</strong></td>
<td><strong>DATE</strong></td>
</tr>
<form action="<?php echo (isset($_POST['go'])) ? 'go.php' : '#'; ?>" method="post">
<input type="hidden" name="liasse" value="<?php echo $_POST['liasse']; ?>"/>
<input type="hidden" name="n_doss" value="<?php echo $_POST['n_doss']; ?>"/>
<input type="hidden" name="qualite" value="<?php echo $_POST['qualite']; ?>"/>
<?php while($row = mysql_fetch_assoc($qry)): ?>
<tr>
<td><input name="data[<?php echo ++$i; ?>][code_s]" type="text" value="<?php echo $row['code_s'];?>" size="10"></td>
<td><input name="data[<?php echo $i; ?>][titre]" type="text" value="<?php echo $row['titre']; ?>" size="45"></td>
<td><input name="data[<?php echo $i; ?>][action]" type="text" value="<?php echo $row['action']; ?>" size="15"></td>
<td><input name="data[<?php echo $i; ?>][libelle]" type="text" value="<?php echo $row['libelle']; ?>" size="55"></td>
<td><input type="text" name="data[<?php echo $i; ?>][date]" value="<?php echo $get_date($row['jour']) ; ?>" size="12"></td>
</tr>
<?php endwhile; ?>
And in order to save this I have this code:
if (isset($_POST['liasse'])) {
$value = $_POST['data'] ;
foreach($value as $key => $array)
{
$sql = 'INSERT INTO agenda SET
liasse = "'.mysql_real_escape_string($_POST['liasse']).'",
code_s = "'.mysql_real_escape_string($array['code_s']).'",
date_action = "'.date('Y-m-d',strtotime($array['date'])).'",
libelle = "'.mysql_real_escape_string($array['titre']).'",
action = "'.mysql_real_escape_string($array['action']).'",
description = "'.mysql_real_escape_string($array['libelle']).'",
n_doss = "'.mysql_real_escape_string($_POST['n_doss']).'",
qualite = "'.mysql_real_escape_string($_POST['qualite']).'"
';
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
}
But I'm really lost,
In fact I use a form for that, now I would like to submit all of this data but without any form, directly when I have the first while I would like to save it.
The thing is that I'm lost because I can not call any var like that data[][code_s].
So I do not know how to save this. I would like to save it in background, and not to display that something has been saved.
Receive all my Utmost Respect
kind regards,
SP.
Wrap the code od the lower code block into a function and hand over the value array as argument:
function storeValues ($data) {
foreach($data as $key => $val)
{
$catalog=sprintf("%s='%s'",$key,$val);
$sql = sprintf('INSERT INTO agenda SET %s', implode(',',$catalog));
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
} // foreach
} // function storeValues
You call this function when you want to save the values. So after retrieving them from the database. You call it for each row you retrieve and hand over the values like that:
storeValues ($row);
This will store one row of values at a time. Obviously this can be optimized to use a multiple insert. But let's take one step after another...

Categories