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

$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.

Related

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 ";

SQL query for list($order_total, $order_id) = mysqli_fetch_array($r); is successful but bugged

I realize a lot of this code is hand waving and show off, and I don't take credit for that. The code successfully executes all the query except the vairable I created for order_id is not returned when I try to show the receipt page with the order_id.
Option 1: Realize that procedures are just functions and rewrite them for debugging
Option 2: Fix the return mysqli_fetch to get the newly created order_id.
So let's start from the beginning of the procedure:
Customer enters Infromation and passes that to procedure add_customer
I save the infromation and then use that customer_id to create a unique order with call add_order
then When I try to get the order Id to create a an email receipt there seems to be a major bug that is unfixable because I have never seen a fetch returned as a list of two variables
$r = mysqli_query($dbc, "CALL add_customer('$e', '$fn', '$ln', '$a1', '$a2', '$c', '$s', $z, $p, #cid)");
// Confirm that it worked:
if ($r) {
mysqli_stmt_execute($r);
echo 'success';
//Retrieve the customer ID:
$r = mysqli_query($dbc, 'SELECT #cid');
//Select the new customer ID
if (mysqli_num_rows($r) == 1) {
list($_SESSION['customer_id']) = mysqli_fetch_array($r);
//$cc_last_four = substr($cc_number, -4);
$cc_last_four = 1234;
// Call the stored procedure:
$shipping = $_SESSION['shipping'] * 100;
$r = mysqli_query($dbc, "CALL add_order({$_SESSION['customer_id']}, '$uid', $shipping, $cc_last_four, #total, #oid)");
echo "success Customer ID to add_order";
//select Order ID
if ($r) {
// Retrieve the order ID and total:
$r = mysqli_query($dbc, 'SELECT #total, #oid');
if (mysqli_num_rows($r) == 1) {
list($order_total, $order_id) = mysqli_fetch_array($r);
echo "Order ID Found";
echo $order_id;
// Store the information in the session:
$_SESSION['order_total'] = $order_total;
$_SESSION['order_id'] = $order_id;
echo $_SESSION['order_total'],
$_SESSION['order_id'];
// Redirect to the next page:
include_once("includes/email_receipt.php");
successsuccess Customer ID to add_orderOrder ID Found
OKAY ILL TRY TO BE QUICK AND QUIT BEATING AROUND THE BUSH
Procedute Add_To_order changed to
BEGIN
DECLARE subtotal INT(10);
INSERT INTO orders (customer_id, shipping, credit_card_number, order_date) VALUES (cid, ship, cc, NOW());
SELECT LAST_INSERT_ID() INTO oid;
END
And the code changed to
$r = mysqli_query($dbc, 'SELECT #oid');
if (mysqli_num_rows($r) == 1) {
list($order_id) = mysqli_fetch_array($r);
echo "Order ID Found";
echo $order_id;
// Store the information in the session:
$_SESSION['order_total'] = $order_total;
$_SESSION['order_id'] = $order_id;
echo $_SESSION['order_total'],
$_SESSION['order_id'];
// Redirect to the next page:
include_once("includes/email_receipt.php");

automatic order id system check existence in mysql database

What I am trying to achieve is I have a systematic order generating system for my website I am just not able to check if the order id already exist if yes then it should increase the number by 1. heres my code end result
for e.g
Order ID: ABCD-00001 (already exist in db then)
New Order ID: ABCD-00002 (and so on...)
$i=0;
$n=1;
while ($i<10000) {
$j = sprintf("%'.05d\n", $n);
$orderid= "ABCD"."-".$j;
$query = mysql_query("SELECT * FROM `orders` WHERE jobid='".$orderid."'") or die (mysql_error());
$num_rows = mysql_num_rows($query);
if ($num_rows > 0) {
$i++; $n++;
} else { $jobid = $orderid;
break; }

How to fetch record from mysql using last inserted id?

This is what i tried and it works fine..
$sql = "SELECT * FROM patient where id = (SELECT max(id) FROM patient)";
result = mysql_query($sql);
if (mysql_num_rows($result) > 0)
{
// output data of each row
while($row = mysql_fetch_assoc($result))
{
$patientid=$row["id"];
$patientname=$row["name"];
$patientrefer=$row["referto"];
$patientdisease=$row["disease"];
}
}
else
{
echo "0 results";
}
but whenever i replaced the query with
$sql = "SELECT * FROM patient where id = LAST_INSERT_ID()";
It always return 0 results.
In order to get last (latest) record from your table, you can do descending ORDER BY together with LIMIT:
SELECT * FROM patient ORDER BY id DESC LIMIT 0,1
You don't need LAST_INSERT_ID in that case at all. Moreover with concurrent inserts you cannot ensure that user's last insert is really the latest one by using LAST_INSERT_ID.

Can Mysqli_query() calls be nested?

I am trying to implement the following code. What I want is to fetch the product id with column name prod_id from the table cart_details and then fetch the details for that product id with column name prod_id from the table products. But this code is not returning anything. Does this means that mysqli_query() calls cannot be nested?
<?php
$cart_id=$_POST['q'];
include "connection.php";
$cart_id=mysqli_real_escape_string($link,$cart_id);
$query="select product_id from cart_details where cart_id = $cart_id";
$result=mysqli_query($link,$query) or die(mysqli_error($link));
if($result)
{
while($row=mysqli_fetch_array($result))
{
$prod_id = $row['product_id'];
$prodDetail = "Select * from products where prod_id = $prod_id";
$prodResult = mysqli_query($link,$prodDetails) or die(mysqli_error($link));
if(!$prodResult){
echo "There was an error in fetching the product with product ID ".$prod_id;
}
else{
if(mysqli_num_rows($prodResult)==0)
{
echo "There is no item in this cart";
}
else{
while($prod=mysqli_fetch_array($prodResult)){
$prod_name=$prod['prod_name'];
$prod_price=$prod['prod_price'];
echo "<tr><td>".$prod_id."</td>";
echo "<td>".$prod_name."</td>";
echo "<td>".$prod_price."</td></tr>";
}
}
}
}
}
else{
echo "Query Failed";
}
?>
Check in your this
$query="select product_id from cart_details where cart_id = $cart_id";
That how many rows you are returning.
You can achieve this by changing this line if($result)
To this
if($result && mysqli_num_rows($result)!=0)
Note mysqli does not automatically secure your applicattion. use bindparam

Categories