简体   繁体   中英

Retrieve shopping cart items from database

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM