Substract Session[cart] QUANTITY to STOCK QUANTITY in db - php

I have a table wich show the ($_SESSION['cart'] with a form inside where I can introduce manually the quantity I want into my ($_SESSION['cart'] PRODUCTS.
<form name="formulario2" method="POST" target="oculto"><input type="hidden" name="action" value="update">
foreach($_SESSION['cart'] as $product_id => $quantity) {
echo "<td align=\"center\"><input type = \"text\" size=\"1\" name=\"qty[$product_id]\" value =\"{$_SESSION['cart'][$product_id]}\"></td>";
}
</form>
Then I use the following to update the ($_SESSION['cart']) quantity
<?php
if(isset($_POST['action']) && ($_POST['action'] =='update')){
//
foreach ($_POST['qty'] as $product_id=> $quantity){
$qty = (int)$quantity;
if ($qty > 0){
$_SESSION['cart'][$product_id] = $qty;
}
}
}
?>
Now I would like to SUBSTRACT those quantities I have UPDATED to the ($_SESSION['cart']) to the quantities in STOCK in my data base.
I think that in the last "foreach ($_POST['qty']" I should also say to substract the QUANTITY UPDATED to the DATA BASE QUANTITY but I dont know how to do it. ANY HELP?

1) Replace value =\"{$_SESSION['cart'][$product_id]}\" with value =\"{$quantity}\". You have it already retrieved in the foreach statement.
2) For the database, having that you use mysql, I would reccommend accessing the database with PDO (I have rewritten your second block of code due to its lack of indentation and not matching parentheses):
<?php
if ((isset($_POST['action']) && ($_POST['action'] == 'update'))
{
foreach ($_POST['qty'] as $product_id => $quantity)
{
$qty = intval($quantity);
$pid = intval($product_id); // ALSO use the intval of the $product_id,
// since it was in a form and it can be hacked
$_SESSION['cart'][$pid] = $qty; // NOTE: you need to also update the
// session`s cart with 0 values, or
// at least to unset the respective
// product:
// unset($_SESSION['cart'][$pid])
if ($qty > 0)
{
// now update the DB:
$mysql_host = "127.0.0.1";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "myShop";
$dbLink = new PDO("mysql:host=$mysql_host;dbname=$mysql_database;charset=utf8", $mysql_user, $mysql_password, array(PDO::ATTR_PERSISTENT => true));
$dbLink->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$query = $dbLink->prepare("update `products` set `stock` = `stock` - ? WHERE `productId` = ? limit 1");
$query->execute(array($qty, $pid));
}
}
}
?>
Hope it works for you!
Regards!

Related

Auto increment a SESSION key ID

I'm having a problem in doing something.
I have this code snippet to add a product to cart:
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "";
$product_name = isset($_GET['product_name']) ? $_GET['product_name'] : "";
$sql = "SELECT * FROM products WHERE product_id LIKE '{$product_id}' AND product_name LIKE '{$product_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if($num == 1)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
if(!isset($_SESSION['cart']))
{
$product_id_session = 1;
}
else
{
$count = count($_SESSION['cart']);
$product_id_session = $count++;
}
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price
);
$_SESSION['cart'][$product_id_session] = $columns;
redirect_to('products.php?&message=added&product_name='. $_SESSION['cart'][$product_id_session]['product_name']);
}
}
As you can see, if the session cart is created, I assign the variable $product_id_session with the count of SESSION arrays plus one. Otherwise, the variable $product_id_session is set to 1. In the cart page I have a link to remove the selected product:
foreach($_SESSION['cart'] as $product)
{
echo "<button onClick=\"location.href='remove.php?product_id_session={$product['product_id_session']}'\">
Remove from cart
</button>";
}
Then, in the remove.php file I have this to process the data from Query String and remove the product from the cart:
$product_id_session = isset($_GET['product_id_session']) ? $_GET['product_id_session'] : "";
unset($_SESSION['cart'][$product_id_session]);
The problem I'm facing is: for example, I added two products in the cart. Then I removed the first product and added another product to the cart. The new product, instead of being added, just will replace the product that was previously added in the cart and the $product_id_session will be always the same value. What I'm doing wrong? How to specify an ID for the SESSION?
You can add new items to the cart just with:
$_SESSION['cart'][] = $columns;
Then it will be appended to end of the array.
And, after deleting item from the array, you can (but it is not necessary) re-index it by
$_SESSION['cart'] = array_values($_SESSION['cart']);
When printing out the cart, you just update the foreach loop to catch the key value into some variable, i.e. $index. The difference is in the $index=>$product part.
foreach($_SESSION['cart'] as $index=>$product)
{
echo "<button onClick=\"location.href='remove.php?product_id_session={$index}'\">
Remove from cart
</button>";
}
Remove.php remains basically the same, I just updated it for better readibility:
if (isset($_GET['product_id_session']) and $_GET['product_id_session']) {
$product_id_session = $_GET['product_id_session'];
unset($_SESSION['cart'][$product_id_session]);
}
Instead of trying to create an extra ID to manage your cart you should just rely on the unique product ID already stored in your database :
if($num == 1) {
$row = $stmt->fetch(PDO::FETCH_ASSOC); // no need for the loop as you only have 1 result
extract($row);
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
// keep track of the added product for the time being
if (!isset($_SESSION['cart'][$product_id])) {
$columns = array(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'amount' => 0, //just add last comma as good practise here
);
$_SESSION['cart'][$product_id] = $columns;
}
//raise the amount
$_SESSION['cart'][$product_id]['amount']++;
redirect_to('products.php?&message=added&product_name='. $_SESSION['cart'][$product_id_session]['product_name']);
}
And change the remove accordingly :
foreach($_SESSION['cart'] as $product) {
echo "<button onClick=\"location.href='remove.php?product_id={$product['product_id']}'\">Remove from cart</button>";
}
EDIT :
To keep an "unique" id you should not use count to calculate the ID
Just use an extra variable to keep track of last Id :
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
$_SERVER['cart_product_id'] = 1;
}
else
{
$_SERVER['cart_product_id']++;
$product_id_session = $_SERVER['cart_product_id'];
}

Foreach loop full execution and stop the rest of the script

I have a product table from where I am checking that quantity for respective product id(s) is valid or not..
this is the code snippet :
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
echo json_encode($array);
exit; /*stop the rest of the code from executing*/
}
}
/*rest of the code outside the loop*/
So here what is happening is it checks the quantity ($quantity_rem) from table of a product id and if that quantity is less than the quantity given ($q), then the script stops and echo the product id..
But I have more that 1 product .. It's not checking the rest since whenever there is a fault it stops and echo out. I want to check all the products and echo out the product id(s) and stop the rest of the script outside the loop..
Help needed!
Thanks.
and please don't talk to me about sql injection because i know it is vulnerable and i will take care of that..
Try this:
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
$errors = array();
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
$errors[] = $array;
}
}
echo json_encode($errors);
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
$array = array();
if($quants > $quantity_rem){
$array[$ps]['errquant'] = 'wrong_quant';
// note little change - you will get array with product ids as key
//and qty error assigned to them
}
echo json_encode($array);
exit; /*stop the rest of the code from executing*/

Comparing from textbox to database

Please help me. I'm having trouble in comparing
How do I compare the quantity that was inserted from the stocks from the database
<?php
session_start();
include_once("config.php");
//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
$return_url = base64_decode($_GET["return_url"]); //return url
session_destroy();
header('Location:'.$return_url);
}
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
$product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url = base64_decode($_POST["return_url"]); //return url
$sel = mysql_query("SELECT * FROM products");
$product_stock = mysql_fetch_assoc($sel);
//limit quantity for single product
if($product_qty > $products['stock'])
{
die('<div align="center">Not enought quantity<br />Back To Products.</div>');
}
Your error is in this line:
if($product_qty > $products['stock'])
What is $products['stock']? Above you defined the MySQL result like that:
$product_stock = mysql_fetch_assoc($sel);
So, did you mean?
if($product_qty > $product_stock['stock'])
Also, your code is vulnerable to redirection-attacks: https://www.owasp.org/index.php/Top_10_2013-A10-Unvalidated_Redirects_and_Forwards
You need to make sure that you somehow validate the parameter return_url, by allowing only a valid list of URLs. Better would be:
$valid_urls = array(1 => 'http://link1.com', 2 => '...');
And then:
$return_url_param = (int)$_GET["return_url"];
$return_url = isset($valid_urls[$return_url_param] ? $valid_urls[$return_url_param] : 'http://defaulturl.com');
You are comparing $product_qty from wrong variable . Try change $products['stock'] to $product_stock['stock'].
Corrected block of code:-
<?php
//add item in shopping cart
if (isset($_POST["type"]) && $_POST["type"] == 'add') {
$product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
$product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url = base64_decode($_POST["return_url"]); //return url
$sel = mysql_query("SELECT * FROM products");
$product_stock = mysql_fetch_assoc($sel);
//limit quantity for single product
if ($product_qty > $product_stock['stock']) {
die('<div align="center">Not enought quantity<br />Back To Products.</div>');
}
}

Multidimensional array in php SESSION

I am having problem with updating an array element with in $_SESSION variable of PHP. This is the basic structure:
$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;
And then by using array_push() function I insert that product in SESSION variable.
array_push($_SESSION['cart'], $product);
Now this is the main part where i m facing problem:
foreach($_SESSION['cart'] as $product){
if($id == $product['id']){
$quantity = $product['quantity'];
$quantity += 1;
$product['quantity'] = $quantity;
}
}
I want to increment product quantity within $_SESSION['cart'] variable. How can I do that?
Don't blindly stuff the product into your session. Use the product's ID as the key, then it's trivial to find/manipulate that item in the cart:
$_SESSION['cart'] = array();
$_SESSION['cart'][$id] = array('type' => 'foo', 'quantity' => 42);
$_SESSION['cart'][$id]['quantity']++; // another of this item to the cart
unset($_SESSION['cart'][$id]); //remove the item from the cart
this not best answers for u...but hope can help u guys
im not expert coders, and just learn coding in this forum ^,^ .You must always trying to solved.
for more example hope can help to update value quantity:
<?php
if(isset($_POST['test'])) {
$id =$_POST['id'];
$newitem = array(
'idproduk' => $id,
'nm_produk' => 'hoodie',
'img_produk' => 'images/produk/hodie.jpg',
'harga_produk' => '20',
'qty' => '2'
);
//if not empty
if(!empty($_SESSION['cart']))
{
//and if session cart same
if(isset($_SESSION['cart'][$id]) == $id) {
$_SESSION['cart'][$id]['qty']++;
} else {
//if not same put new storing
$_SESSION['cart'][$id] = $newitem;
}
} else {
$_SESSION['cart'] = array();
$_SESSION['cart'][$id] = $newitem;
}
}
?>
<form method="post">
<input type="text" name="id" value="1">
<input type="submit" name="test" value="test">
<input type="submit" name="unset" value="unset">
</form>
I faced the same issue before, and the accepted answer works only because it modifies the session variable directly, but in a foreach loop, you must pass the $product variable by reference (by prepending & to it) to be able to save changes like this :
foreach($_SESSION['cart'] as &$product){
if($id == $product['id']){
$product['quantity'] += 1;
}
}
Or if you follow the accepted solution :
foreach($_SESSION['cart'] as $id => &$product){
if($searchId == $id){
$product['quantity'] += 1;
}
}

adding to database inside a foreach loop based on a specific variable in php

I have a shopping cart that has a text box to update the quantity of each item. When a user clicks the update button I loop through each of the items and update their quantities in the database table holding the cart information. Now I am adding a gift card feature and I am running into a problem. When a user updates the quantity of a certain price gift card I need to not only update the carts table but also create another gift card with a unique card number. I am trying to figure out how to add another gift card if the item is a gift card while in the foreach loop. Here is the code I have for updating the quntities:
foreach ($_POST['quantity'] as $sku => $qty) {
list($pid, $szid) = explode("-", $sku);
if ($pid) { $pid=trim($pid);}
if ($szid) { $szid=ltrim($szid);}
if (isset($pid, $szid)) {
$qty = (filter_var($qty, FILTER_VALIDATE_INT, array('min_range' => 0))) ? $qty : 1;
$r = mysqli_query($dbc, "CALL update_cart('$uid', $pid, $qty, $szid)");
}
}
This code works exactly as I want it to updating the quanities of the cart items. Now I cant figure out how to alter this for checking if the $pid is 1 and adding a new gift card to the gift card table if it is. Here is my best attempt but it doesnt seem to work:
foreach ($_POST['quantity'] as $sku => $qty) {
list($pid, $szid) = explode("-", $sku);
if ($pid) { $pid=trim($pid);}
if ($szid) { $szid=ltrim($szid);}
if (isset($pid, $szid)) {
$qty = (filter_var($qty, FILTER_VALIDATE_INT, array('min_range' => 0))) ? $qty : 1;
$r = mysqli_query($dbc, "CALL update_cart('$uid', $pid, $qty, $szid)");
while($pid == 1 ) {
$gcn = md5(uniqid('biped', true));
$card = 'GC'.$gcn.'';
$amt = $_POST['price'];
// Add to gift card table
$r = mysqli_query($dbc, "CALL add_gift_card('$szid', '$uid', '$card', '$amt')");
}
}
}
I need the code to check how many $qty there are for the gift card $pid and run the add_gift_card query for each $qty where the $pid is equal to 1.
Oh and here is the form in case you want to see it:
echo'<input type="text" class="cart-item-quantity" name="quantity['.$cart['sku'].']" value="'.$cart['quantity'].'" size="" />';
echo'<input type="hidden" name="price" value="'.$price.'" />';
Any help or guidance would be great.
if ($pid == 1) {
for ($i = 0; $i < $qty; $i++) {
$gcn = md5(uniqid('biped', true));
$card = 'GC'.$gcn.'';
$amt = $_POST['price'];
// Add to gift card table
$stmt = mysqli_prepare($dbc, "CALL add_gift_card(?, ?, ?, ?)";
mysqli_stmt_bind_param($stmt, 'sisi', $szid, $uid, $card, $amt);
$r = mysqli_stmt_execute($stmt);
}
}

Categories