I'm developing a shopping cart using php, now I stuck at some point as follow.
There are tables like: customers, products, orders, order_detail
products table:
id | name | quantity
order_detail table:
order_id | product_id | quantity
I completely done for add product to cart and customer can submit the order to database, admin can remove or delete orders from backend and customers can remove orders list or delete orders from frontend if that ordered still not confirm payment.
Example:
"customer1" order 10 products, order ID is #907987899 and "product1" customer1 order quantity = 2, "product2" customer1 order quantity = 5 and so on.....
if the ordered still not confirm then customer still can remove product from the ordered list, and also can delete the entire ordered.
My problem now is: if Customers or Admin cancel or delete the ordered that still not confirm payment then I want to return product quantity from order_detail table list back to products table. by the time when customer submitted the order then product quantity is subtract from product table.
Here is my code that return quantity back to products:
require '../../init.php';
require $ROOT . '/functions/basic.php';
if(isset($_POST['id']))
{
$id = htmlspecialchars($_POST['id']);
$delete = dbQuery("DELETE FROM orders WHERE order_id = '$id'");
if($delete == true)
{
//unlink($ROOT . '/upload/products/' . $image);
$select_product = dbAll("SELECT product_id, quantity FROM order_detail WHERE order_id = '$id'");
foreach($select_product as $product)
{
$quantity = $product['quantity'];
$product_id = $product['product_id'];
$return_product_quantity = dbQuery("UPDATE products SET quantity = (quantity + $quantity) WHERE product_id = $product_id");
}
if($return_product_quantity == true)
{
$delete_order_detail = dbQuery("DELETE FROM order_detail WHERE order_id = '$id'");
if($delete_order_detail == true)
{
echo "OK";
}
else
{
echo "Can't delete order detail information";
}
}
}
else
{
echo "Can't delete order row";
}
}
but the query it seem not work as my required, so please help me how to handle this kind of logic to perform my required.
Thanks in advance.
You are trying to use the variable quantity in your UPDATE even though it has no value. Try this instead:
$return_product_quantity = dbQuery("UPDATE products
SET quantity = ((SELECT quantity FROM products WHERE product_id = $product_id) + $quantity)
WHERE product_id = $product_id");
Related
I have been trying to create a persistent MySQL-based shopping cart application starting from a session-based php shopping cart. The cart table has the structure userid | productid | quantity | postingdate.
In the session-based implementation, the quantity info for a certain product was stored in $_SESSION['cart'][$row['id']]['quantity'];; I am facing trouble with retrieving the quantity info for a certain product from the cart table in the database because I can't seem to find how to extract the productId necessary for the $getquantity query.
$sql1 = "SELECT * FROM cart WHERE userid='$userId'"; //selects the user's cart
$query1=mysqli_query($con,$sql1);
if (!empty($query1)) { //if the user's cart isn't empty
while($row = mysqli_fetch_array($query1)){
$query = mysqli_query($con,"SELECT * FROM products JOIN cart ON cart.productid=products.id
ORDER BY cart.postingDate DESC"); //selects all the products in the current user's cart
}
$totalprice=0;
$totalqunty=0;
if (!empty($query)) {
while ($row = mysqli_fetch_array($query)) { //for each product
//$quantity=$_SESSION['cart'][$row['id']]['quantity']; //SESSION IMPLEMENTATION
$id = $row['id'];
$quantity = mysqli_query($con,"SELECT quantity FROM cart WHERE userid='$userId' AND productid='$id'"); //MY IMPLEMENTATION, THE WRONG PART IS WITH $id
$subtotal= $quantity*$row['productPrice']+$row['shippingCharge'];
$totalprice += $subtotal;
$_SESSION['qnty']=$totalqunty+=$quantity; //SESSION IMPLEMENTATION
}
}
}
I've tried $row['id'] but it returns an array of all the productid from the records returned by $query and MySQl doesn't seem to accept it, while instead I need the $getquantity to run on each productid. Please don't mind how it's vulnerable to SQL injections as I will get to that in later stages.
Here's a working solution: I could have just selected the cart.quantity attribute (considering how the products and cart table were joined):
$sql1 = "SELECT * FROM cart WHERE userid='$userId'"; //selects the user's cart
$query1=mysqli_query($con,$sql1);
if (!empty($query1)) { //if the user's cart isn't empty
while($row = mysqli_fetch_array($query1)){
$query = mysqli_query($con,"SELECT products.productImage1 , products.productName ,
products.id, cart.productId, cart.quantity as qty, products.productPrice,
products.shippingCharge FROM products JOIN cart ON cart.productid=products.id
ORDER BY cart.postingDate DESC"); //selects all the products in the current user's cart
}
$totalprice=0;
$totalqunty=0;
if (!empty($query)) {
while ($row = mysqli_fetch_array($query)) { //for each product
$quantity=$row['qty'];
$subtotal= $quantity*$row['productPrice']+$row['shippingCharge'];
$totalprice += $subtotal;
}
}
}
So I have this MySQL table where an item has a field called isCoupon. The default is set to 0 if the seller does not make the item available for coupon use. Each item is ordered by ID and in the shop, there can be more than one coupon where the item is also available for discount. But how do I make it that those coupons display when the item is included? How do I make it that the buyer gets to pick which coupon to use? And how do I calculate the new price if I put "50% off" on the record instead of 0.5?
Table Coupon
couponCode | items | discount
------------------------------
SAMPLE123 | 1 | 50% off
SAMPLE234 | 2,3 | 40% off
SAMPLE345 | 1,5 | 25% off
Table Item
itemID | isCoupon
-----------------
1 | 1
2 | 1
3 | 1
4 | 0
5 | 1
Thanks!
Try the below. As for the buyer picking to choose which coupon, you should let the buyer select the item first and then go to the checkout page by selecting the coupon.
$num_items = 5;
// the below array is used to store the coupons you can use for the item so you can
// proceed with it to the checkout page, there you can make a select dropdown to let
// the buyer select which coupon to use
$coupon_use = array();
for($i = 0; $i < $num_items; $i++) {
// check for current item
$SQL = "SELECT * FROM item WHERE itemID = '$i'";
$result = mysqli_query($connect, $SQL);
$field = mysqli_fetch_assoc($result);
// check if there is a coupon for the current item
if($field['isCoupon'] == 1) {
$SQL2 = "SELECT * FROM coupon";
$result2 = mysqli_query($connect, $SQL2);
// while method to go through every single coupon
while($field2 = mysqli_fetch_assoc($result2)) {
// if you put commas, you can use the explode method
// to store all the items for that coupon and use it to
// check for that current item
$coupons = explode(',', $field2['items']);
if(in_array($i, $coupons)) {
// do your items have a price?
// salePrice is the new price
// thePrice is the old price you need to get with $field (not $field2)
if($field2['discount'] == '50% off') { $salePrice = $thePrice * 0.5; }
else if($field2['discount'] == '40% off') { $salePrice = $thePrice * 0.6; }
else if($field2['discount'] == '25% off') { $salePrice = $thePrice * 0.75; }
// add the coupon code to the array of coupons available for use
array_push($coupon_use, $field2['couponCode']);
// display the prices
echo 'ITEM #'.$i.'<br><s>$'.$thePrice.'</s><br>$'.$salePrice.'<br><br>';
}
}
}
else { echo 'ITEM #'.$i.'$'.$thePrice; }
}
Now you can store the values of the coupon_use array to the checkout page.
I'm trying to implement a shopping cart for my website. My page loops through products in my database and displays them on the page with an 'Add' button. You can only add an item if you are logged in.
Products Table
| ID | Name | Price | Quantity | description | image_name |
Once you add an item it stores this in my cart table. The 'CartProduct int' is the same as the 'ID' in my products table.
Cart table
| CartID | CartProduct | ProductCount | UniqueID | Username | Date
If you click Add on the same product, the ProductCount will increment.
So if TestUser adds CartProduct 1 & 2 and 2 again.
I'm really unsure on how to display all products WHERE username 'TestUser' and I also need ProductCount * Price.
At the moment I'm trying to loop through each CartProduct for the logged in user, then select the ID from products table WHERE ID = CartProduct (as they are the same). I can then grab the price and details of that product.
At the moment I am selecting from cart where username = username that is logged in. Just so I can see the outcome, I am displaying it.
$sql = "SELECT cartProduct FROM cart WHERE username ='" . $name . "'";
$result = mysql_query($sql);
$c = 0;
$n = 2; // Each Nth iteration would be a new table row
while ($db_field = mysql_fetch_assoc($result)) {
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$productNo = $row['cartProduct'];
if ($c % $n == 0 && $c != 0) { // If $c is divisible by $n...
echo '<div class="row" ></div>';
}
$c++;
echo "<br>Count: " .$c;
?>
<h2> <?php echo "Product No: " . $productNo ?> </a></h2>
<?php
I add 3 items to the cart. CartProduct 1, 2, 2 :- for the output I keep getting:
Product No: 1
Product No: 1
I should see Product 1 and then Product 2?
Am I making this more complicated than it should be, and are my tables correct?
Is there an easier way?
Many thanks for any replies!
First, in Cart Table change Username to UserId.
The next one step is modify sql query at "JOIN products" to get connect with Products Table and easly get a product price.
But in general, use PDO driver to get more safeties and clearlies queries and PHP code. Read about relations in DB (RDBM).
I have two table in mysql that is product and sell. The product contain the stock and the sell contain the purchasing record. Now i want to sell a product from the stock when i insert the quantity of selling item into the sell table then the same amount should be decrease in the stock that is product table. Please help me for the query.
Sell table insertion.
$cus_id = $_POST['customer'];
$reg_id = $_POST['cus_region'];
$cat_id = $_POST['product'];
$name = $_POST['name'];
$price = $_POST['unit_price'];
$quantity = $_POST['quantity'];
$date = $_POST['datepicker'];
$total = $price * $quantity;
$payment = $_POST['payment'];
$remainig = $total - $payment;
$query = "INSERT INTO sell SET cus_id = '".$cus_id."',reg_id = '".$reg_id."', cat_id = '".$cat_id."',product = '".$name."',selling_price = '".$price."',selling_date = '".$date."',item_quantity = '".$quantity."',amount_paid= '".$payment."',total_price = '".$total."', remaining = '".$remainig."'";
$res = mysql_query($query);
Two way to resolve that,
1) if you are getting the quantity of product you can make second query to deduct the quantity from stack table (product table)
2) You can use trigger for such operations, while you insert in to sales table that same quantity you can reduce from the product table
You have to just change or decrease the quantity of the product in PRODUCT table. So, you have to use UPDATE query.
This can solve your issue:
1) I consider that your cat_id is the unique product key to identify a product in your PRODUCT table.
2) I consider that you have quantity column in PRODUCT table, which store the quatity of the product. And 1 product is being sold at a time.
UPDATE TABLE_NAME SET quantity=quantity - 1
WHERE cat_id = "SOME_INT_ID_WITHOUT_QUOTES"
I am working on 3 tables linked with foreign keys and also set to ON UPDATE CASCADE and ON DELETE CASCADE. These tables are category, subcategory and products.
products table - PID(PK), productname, subcatid(FK)
subcategory table - subcatid(PK), subcategoryname, catid(FK)
category table - catid(PK), categoryname
What is the right query to UPDATE products table when I want to change the name of the product? Also if I want to change the subcategory of a product by using a form?
I am using a form which successfully prepopulates with the fields - product name, subcategory name but it does not update the records in products table, means it does nothing and does not changes the product name and subcategory name.
Any help is appreciated.
am using the following code
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['PRODUCT_NAME'])) {
$pid = mysql_real_escape_string($_POST['thisPID']);
$catalog_no = mysql_real_escape_string($_POST['CATALOG_NO']);
$product_name = mysql_real_escape_string($_POST['PRODUCT_NAME']);
$price = mysql_real_escape_string($_POST['PRICE']);
$composition = mysql_real_escape_string($_POST['COMPOSITION']);
$size = mysql_real_escape_string($_POST['SIZE']);
$subcat = mysql_real_escape_string($_POST['SUBCAT_ID']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("UPDATE products SET CATALOG_N0='$catalog_no', PRODUCT_NAME='$product_name', PRICE='$price', COMPOSITION='$composition', SIZE='$size', SUBCAT_ID='$subcat' WHERE PID='$pid'");
header("location: inventory_list.php");
exit();
}
?>
<?php
// Gather this product's full information for inserting automatically into the edit form below on page
if (isset($_GET['pid'])) {
$targetID = $_GET['pid'];
$sql = mysql_query("SELECT products.PID, products.CATALOG_NO, products.PRODUCT_NAME, products.PRICE, products.COMPOSITION, products.SIZE, products.SUBCAT_ID, subcategory.SUBCAT_ID, subcategory.SUBCATEGORY_NAME FROM (products, subcategory) WHERE subcategory.SUBCAT_ID=products.SUBCAT_ID AND PID='$targetID' LIMIT 1");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$catalog_no = $row["CATALOG_NO"];
$product_name = $row["PRODUCT_NAME"];
$price = $row["PRICE"];
$composition = $row["COMPOSITION"];
$size = $row["SIZE"];
$subcat = $row["SUBCAT_ID"];
}
} else {
echo "You dont have that product";
exit();
}
}
?>
You're not using the product name as a foreign key, so a simple standard
UPDATE products SET productname='New Name of Product' where PID=XXX;
would do the trick. Same goes for the subcatid in products. As long as the new subcat ID exists in the subcategory table, you can change products.subcatid to whatever you want, again via a simple
UPDATE products SET subcatid=New_ID where PID=XXX;