Inventory count of my database keeps starting at 28? - php

I am new to coding and in my code and i am having trouble updating my database.
I am using mysql and php to create a shopping cart that updates inventory when an item is purchased. The cart takes the product id of the item and stores it using the GET array. The problem is that after someone purchases an item, the inventory doesn't adjust probably in my database. the inventory count always starts at 28 every time I purchase an item instead of starting at the proper inventory amount. The code for the shopping cart is:
require 'connect.php';
require 'item.php';
if(isset($_GET['id'])){
$result = mysqli_query($con, 'select * from products where
id='.$_GET['id']);
$products = mysqli_fetch_object($result);
$item = new Item();
$item->id = $products->id;
$item->name = $products->name;
$item->price = $products->price;
$item->quantity = 1;
$_SESSIONS['id']=$_GET['id'];
// Check if the products exists in the cart
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0; $i<count($cart); $i++)
if($cart[$i]->id==$_GET['id'])
{
$index = $i;
break;
}
if($index==-1)
$_SESSION['cart'][] = $item;
else{
$cart[$index]->quantity++;
$_SESSION['cart'] = $cart;
}
}
// Delete products in cart
if(isset($_GET['index'])){
$cart = unserialize(serialize($_SESSION['cart']));
unset($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
if(array_key_exists('submit2', $_POST))
{
$results = mysqli_query($con, "select * from products");
$sql="";//init
while($products=mysqli_fetch_object($results)){
for($i=0; $i<count($cart); $i++){
$idcart=$cart[$i]->id;
$quantity= $products->quantity;
$cartquantity = $cart[$i]-> quantity;
$sql= "UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';";//u need this to append the query
session_destroy(); }//end for
}//end while
if ($con->multi_query($sql) === TRUE) {//use multi_query
header("location: thankyou.php");
} else {
echo "Error updating record: " . $con->error;
}
$con->close();
I believe the problem is in this code here. $sql= "UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';";. Any help will be appreciated. Thank you!

The whole logic around updating the cart quantities seems to be unusual. You have a loop which loops over all of the products and then updates a somehow related database record based on the id from the cart with the quantity from the product. There is no attempt to match the quantity from the product ID with the ID from the cart.
This code just loops through the cart and reduces the quantity of the matching product for each row, it also prepares the statement before the loop and just executes it once for each row...
if(array_key_exists('submit2', $_POST))
{
$sql = "UPDATE products
SET quantity = quantity - ?
WHERE id= ?";
$stmt = $conn->prepare($sql);
foreach ( $cart as $item ){
$stmt->bind_param('ii', $item->quantity, $item->id );
$stmt->execute();
}//end foreach
session_destroy();
}//end if

You could use the quantity values directly in update
$sql = "UPDATE products SET quantity= quantity - ? WHERE id= ? ;"
$stmt = $con->prepare($sql);
$stmt->bind_param('ii', $cartquantity, $idcart, );
$stmt->execute();

You forgot to concatenate your multi query sql on the line with this code:
$sql= "UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';"
Please put concat operator like this:
$sql .= "UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';"
Or like this:
$sql= $sql."UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';"
I noticed you are executing your update SQL after loop which is fine but without concatenation you are only executing the last query in your loop.

Related

I want to update the stock in the database upon clicking submit, but it stores a wrong input

Here is my code to insert the checked values from checkbox to database. I intend to update the stock from another table after I click submit, but it stores an incorrect input. For ex: If I entered 5 quantity on checkout page, instead of decreasing the number of stock, it inputs a negative value of what I entered: -5.. What seems to be the problem here?
<?php
include 'config.php';
$invoice = $_POST['invoiceid'];
if(isset($_POST['submit'])){
$checked_array=$_POST['prod'];
foreach ($_POST['prodname'] as $key => $value) {
if(in_array($_POST['prodname'][$key], $checked_array)){
$product=$_POST['prodname'][$key];
$price= $_POST['price'][$key];
$qty= $_POST['qty'][$key];
$amtpaid = $price * $qty;
$query = "INSERT INTO purchasedproducts SET invoice_id='$invoice', productname='$product', quantity='$qty', amtpaid='$amtpaid'";
$run = mysqli_query($link,$query);
//select product_stock table
$stock_table = mysqli_query($link, "SELECT * FROM product_stock");
$stock = $row['qty_stock'] - $qty;
$update_que = "UPDATE product_stock SET qty_stock='$stock' WHERE product_name='$product'";
$run_update = mysqli_query($link,$update_que);
}
}
}
header('Location: sample.php');
?>
Your query is updating the column value with your "input". What you are wanting is something like this.
$update_que = "UPDATE product_stock SET qty_stock=qty_stock+'$stock' WHERE product_name='$product'";
This is setting the value to its original value plus the input.

How to insert stock quantity and update into another table?

I'm trying to update the quantity of stock when a new stock is added. I'm using array because I want to add more than one product in the page. But the data is not insert into the db and no update on the quantity of stock too. What do I miss on this code?
<?php
include 'db_connection.php';
if(isset($_POST["submit4"])){
foreach($_POST['fk_product'] as $index => $searchid){
$sql="INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";
$quantity_bal=$_POST['quantity_bal'];
if($quantity_bal==0){
$sql="UPDATE product set quantity_bal= quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}else if($quantity_bal!=0){
$sql="UPDATE product set quantity_bal= quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}
$query = mysqli_multi_query($conn,$sql);
if($query){
header("location:product.php");
}
}
}
?>
What you're missing is that you need to concatenate the queries, with the use of = assignment operator, you've just overridden the former string, so it should be like this
foreach($_POST['fk_product'] as $index => $searchid){
$sql = "INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";
$quantity_bal = $_POST['quantity_bal'];
if($quantity_bal == 0){
//I'm presuming that the quantity_ori is a variable here 'coz you're trying to sum up with the original to the latest one
$sql .= "UPDATE product set quantity_bal= $quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}else if($quantity_bal != 0){
$sql .= "UPDATE product set quantity_bal= $quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}
}
We changed the = symbol in your update queries into .= and then your quantity_ori earlier doesn't have the $ symbol, since we're presuming it's a variable, don't forget the $

How do I fix 'Trying to get property of non-object' for PHP?

What I am basically trying to do is run through a loop to look through all inventory slots in the player's inventory and figure out what item ids they are and throwback item names when the player goes onto the inventory page, I have that working.
The issue comes when I want to include quantity and I want to iterate through every slot_x_quantity table in the database in one fell swoop, but I keep getting errors like
Undefined index: 'slot_1_quantity''
I am putting $selectstatement in the query to find the quantities because I want to be able to go through slot_x_quantity 1-9 in the loop.
I've tried not even having $selectstatement and doing $query = "SELECT slot_'$indexaddone'_quantity FROM inventory WHERE char_id='$char_id'";
But then $result throws false, as if it is not able to find the table(s).
foreach($char_inv_slots as $key=>$value) {
if($value != 0) {
$item_id = $value;
$query = "SELECT item_name FROM items WHERE id='$item_id'";
$result = mysqli_query($db, $query);
$row = $result->fetch_assoc();
$item_name = $row['item_name'];
$indexaddone = (int)$key + 1;
$selectstatement = "slot_" . $indexaddone . "_quantity";
$query = "SELECT '$selectstatement' FROM inventory WHERE char_id='$char_id'";
$result = mysqli_query($db, $query) or die($query->error);
$row = $result->fetch_assoc();
$item_quantity = $row["'$selectstatement''"];
if($value == 8001) {
echo($item_name . " - " . $item_quantity);
} else {
echo($item_name . "<br>");
}
I want, on my inventory page, to see the " - " with only items that are stackable, but I can't seem to get the quantitys to show through this loop.
Use this code it will return only set row value and escape if row is not set already
$row = $result->fetch_assoc();
$item_quantity = isset($row[$selectstatement]) ? $row[$selectstatement] : "0";
It will show your Item name with item quantity if any otherwise show item name with item quantity 0.
Also Replace $row["'$selectstatement''"]; To $row[$selectstatement];
Make sure 'slot_1_quantity' etc present in your row from where you are fetching the records otherwise item quantity will remains 0 every time.

How to insert different size of same product in cart or database?

I'm creating a basic e-commerce site with PHP and MySQL. When I click on add to cart in product page it will add to cart but if I click on same product but different size it will not insert into cart. Can someone help me solve my issue? I'm beginner in PHP and MySQL.
This is my code:
if (isset($_POST['add_cart'])) {
$the_product_id = $_GET['p_id'];
$size = $_POST['size'];
$quantity = $_POST['quantity'];
$query = "SELECT * FROM carts WHERE cart_user_id='{$user_id}' AND cart_product_id=' {$the_product_id}' ";
$select_from_product = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($select_from_product)) {
$cart_product_id = $row['cart_product_id'];
$cart_product_size = $row['cart_product_size'];
}
if ($cart_product_id == null || $cart_product_id == ' ' && $cart_product_size == null) {
$addquery = "INSERT INTO carts(cart_user_id, cart_product_id, cart_product_quantity, cart_product_size) VALUES('{$user_id}','{$the_product_id}','{$quantity}','{$size}')";
redirect("cart.php");
$add_to_cart = mysqli_query($connection, $addquery);
$p_query = "UPDATE product SET product_quantity= product_quantity-$quantity WHERE product_quantity > 0 and product_id = '{$the_product_id}'";
$up_query = mysqli_query($connection, $p_query);
} else {
echo "This product already to your cart";
}
You are checking the product existence in cart using product id and user id.
$query = "SELECT * FROM carts WHERE cart_user_id='{$user_id}' AND cart_product_id=' {$the_product_id}' ";
So if you select a product first time then it is added. Second time when you try to add the product in cart, there is already a product with same product id, but with different size in cart. so following condition is never fulfilled.
if($cart_product_id == null || $cart_product_id == ' ' && $cart_product_size == null ){
You need to include size in where clause of first query i.e
$query = "SELECT * FROM carts WHERE cart_user_id='{$user_id}' AND cart_product_id=' {$the_product_id}' ";
Also redirect should be after queries. But that is another issue.
There are other issues in code too. So this answer is related to your specific question.
$query = "SELECT * FROM carts WHERE cart_user_id='{$user_id}' AND cart_product_id=' {$the_product_id}' AND cart_product_size = $size ";

The stock was out of limit, still insert into order table

$prodqty = mysql_query("SELECT quan FROM pro_list WHERE auto_id = $pid"); //get the current product quantity
if (mysql_num_rows($prodqty) != 0)
{
$row = mysql_fetch_array($prodqty);
$productqty = $row['quan'];
}
$nqty = $productqty-$q; //current product quantity minus order quantity to get new product quantity
if ($nqty >= 0)
{
$query2="UPDATE pro_list SET quan = $nqty WHERE auto_id = $pid"; //update the quantity in the product table
$result = mysql_query($query2);
if ($result)
echo "Successfully ";
else
echo "Unsuccesfully";
}
else
echo "Limit of quantity! .";
}
die('Thank You For Shopping With i-Supply System! your order has been sent to Admin.!');
}
the stock was out of limits, but the orders still insert into database. the order should not insert into table order because it already out of limit the quantity of products. Customer should make an order again. Why this should happen?
Your approach is fundamentally flawed. You will get a race condition if two or more updates are attempted at the same time. You should perform the check and update as a single query like this:
$query="UPDATE pro_list SET quan=quan-$q WHERE auto_id=$pid and quan>=$q";
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows() == 0) {
echo "Out of stock!";
}
In any case, you shouldn't be using mysql - it's deprecated. Use mysqli or PDO instead.

Categories