简体   繁体   中英

e commerce site, add to basket error. (php help)

I have a problem with php

I am building an e-commerce site (coursework for uni) and I am creating the add to basket part.

I am able to add a product to the basket (with title, price, ID & quantity displayed) however, whatever product I add to the basket it always displays the title, price & ID of the first product in the database.

(For example I can add 2 items to the database, and they will both have the title of the first item in the database)

(Code for displaying products in basket below) Thank you

if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0){ 
    foreach($_SESSION['cart'] as $product_id => $qty){

        $sql = "SELECT  post_title, price, post_id FROM products"; 
            $result = mysql_query($sql);

            if(mysql_num_rows($result) > 0) {
            list($name, $price, $id) = mysql_fetch_row($result);

                echo "ID " . $product_id . " " . $name ." " . "Price : " . $price . " DB ID " . $id ." Quantity = " . $qty . "<br/>";
            }
    }

echo "<td colspan=\"3\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?empty\" onclick=\"return confirm('Are you sure?');\">Empty Cart</a></td>";

}else{

echo "0";
}

You need to add a WHERE clause to your query.

$sql = "SELECT  post_title, price, post_id FROM products WHERE `id` = '$product_id'"; 

Presently all your query is doing is taking everything out of the database table, and then you are selecting the first row.

The WHERE clause limits your query to only take the row of the matching product, note that you may need to alter the column name for your product id column.

Although a personal recommendation, instead of fetching the product from the database on each page load, Assuming that no one is going to add exuberant amounts of products to your cart just store the product information in the cart session key as well.

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