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).
Related
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 have a page that has a column "order". When I add a new item the order should be 1 + max of the item. But if I delete an item between these values like i have 8 9 10 , if I delete item with 9 the new item will have 11 value and I will have 8 10 11.But I want 8 9 10. How can I do this in php? should I create a function? It works to add a new item with the max+1, but if I delete is not good.
My code:
$queryMaxOrd = mysql_query("select max(ord) from article where user_id=" .$_SESSION['userId']);
$row = mysql_fetch_row($queryMaxOrd);
$valueMaxOrd = $row[0] + 1;
$_SESSION['a'] = $valueMaxOrd;
and the insert query....
Any ideas?
First thing to consider is removing mysql_* and start using mysqli_* or pdo. Your code is vulnerable to sql injections.
With your code structure you have you adding each order as a new record to your table, so when you have 5 orders with one users your table will look like this.
user: Adiiia | order: 5
user: Adiiia | order: 3
user: Adiiia | order: 7
user: Adiiia | order: 2
user: Adiiia | order: 9
when you query the database you are saying to mysql: get me the maximum number of the record i have with user: Adiiia. The result should be 9
If you want to count the sum of the records you should use sum
select sum(ord) from article where user_id='".$_SESSION['userId']."'
The result should be 26
The best thing you can do is by creating a new table orders_sum
The structure should like like this.
Total_orders | User
when a user have a new order you can update the table by adding one or else if have a order removed then removing minus one order.
Something like this.
Total_orders | User
5 | Adiiia
When you want to update:
select Total_orders from orders_sum where User='Adiiia'
Find how many orders the user have by fetching the table.
$orders = $row['Total_orders'];
$plus_orders = $row['Total_orders'] + 1;
update orders_sum set Total_orders='".$plus_orders."' where user='Adiiia'
When you want to delete:
select Total_orders from orders_sum where User='Adiiia'
Find how many orders the user have by fetching the table.
$orders = $row['Total_orders'];
$minus_orders = $row['Total_orders'] - 1;
update orders_sum set Total_orders='".$minus_orders."' where user='Adiiia'
Lets say article table having primary key article_id then after delete any article for user_id. Fetch all the article_id for the user_id. Then update the order for all the article_id for that user.
$queryArticle = mysql_query("select article_id from article where user_id=" .$_SESSION['userId']." order by article_id asc");
$allArticle = [];
while($rowArticle = mysql_fetch_assoc($queryArticle)){
$allArticle[] = $rowArticle['article_id'];
}
$query = "UPDATE article SET ord = (CASE order ";
foreach($allArticle as $order => $article_id) {
$query .= " WHEN {$article_id} THEN {$order}";
}
$query .= " END CASE) WHERE article_id IN (" . implode(",", $allArticle) . ")";
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");
I am working on a php project with MySQL as database. Here is the table structure
product_id (PK)
shop_id (FK)
product_name
product_desc
Product_id is the primary key and shop_id is the foreign key (shows the product belongs to which shop). Now I want to select these product and display them in a <div>. For each shop products, I want to display a different <div>. e.g if there are three products say p1,p2 and p3, and they have same shop_id (say) 1, i want them to show in a separate <div>. there will be separate <div> for each shop_id, and all products belong to that shop_id will be displayed in that <div>. How can I do this with My_SQL query or using PHP. I have used a simple SELECT query like this but with this i could not find a way to initiate different <div> for separate shop.
$q = mysql_query("SELECT * FROM table");
echo "<div>";
while($product = mysql_fetch_assoc($q)){
echo $product['product_name']."<br/>";
}
echo "</div>";
It just throw all products in a single dive, I want separate div for separate shop (which contains all products of that shop). Thanks for reading..
Simplest way is to group the products by id in a array and loop through them
$all_products = array();
while($product = mysql_fetch_assoc($q)){
$all_products[$product['shop_id']][] = $product;
}
foreach($all_products as $shop_id => $product_array){
echo "<div id='shop_".$shop_id."'>";
foreach($product_array as $product){
echo $product['product_name']."<br/>";
}
echo "</div>";
}
OR call product data fro each shop id
$q = mysql_query("SELECT * FROM shops");
while($shops = mysql_fetch_assoc($q)){
$product_q = mysql_query("SELECT * FROM product_table WHERE shop_id=$shops['id']");
echo "<div>";
while($product = mysql_fetch_assoc($product_q)){
echo $product['product_name']."<br/>";
}
echo "</div>";
}
I have two queries, $myDataID1 and $myDataID2.
I am able to print $myDataID1 with a while loop and mysql_fetch_assoc. I want to print the second query results ($myDataID2) below the $myDataID1 results. When I do this I almost get what I want... All rows are returned for the first query but unfortunately only 1 row of data for the second query. I am using a "GROUP BY" so that information isn't duplicated. Without the group by I am getting all the data - but its repeated over and over again and wastes a lot of bandwidth.I guess I want to IMPLODE the mysql_fetch_assoc array so I can compare values with an "if" statement from the two queries.
Essentially, I want this:
Product 1 (from the product table)
This is the product description (from the product table)
inventory item 1 (from the inventory table)
inventory item 2 (from the inventory table)
inventory item 3 (from the inventory table)
Product 2 (from the product table)
This is the product description (from the product table)
inventory item 1 (from the inventory table)
inventory item 2 (from the inventory table)
inventory item 3 (from the inventory table)
heres the php:
<?php
$myDataID1 = mysql_query("SELECT DISTINCT inventory.id, sections.sku,
inventory.release_date, inventory.version, inventory.season,
product.description, inventory.price
FROM inventory INNER JOIN product
ON inventory.id=product.id
GROUP BY product.description
ORDER BY title, id ", $connectID);
$myDataID2 = mysql_query("SELECT product.title, product.description,
product.type
FROM product
WHERE product.type='NEW'", $connectID);
while ($row = mysql_fetch_assoc($myDataID1)) {
{
print '<strong>';
print $row["title"];
print '</strong>';
print $row["description"];
}
print 'Season: ';
print $row["season"];
print $row["id"];
print '/';
print $row["sku"];
print ' -$';
print $row["price"];
print $row["version"];
print ' Version)';
print $row["release_date"];
}
?>