简体   繁体   中英

PHP Shopping cart, adding multiple items

if (!empty($_GET['action'])) {
    $j = $_GET['id_'];
    switch($_GET['action']) {
        case "add":
        $query = "select * from ogl where id = $j";
        $result = mysqli_query($conn, $query);
        $row = mysqli_fetch_assoc($result); 
        $array = array($row["id"]=>array('seller'=>$row["seller"], 
        'name'=>$row["name"], 'cpu'=>$row["CPU"], 'size'=>$row["size"], 
        'price'=>$row["price"], 'img'=>$row["img"])); 

        if (empty($_SESSION["cart_item"])) {
            $_SESSION["cart_item"] = $array;
        } else {
            $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"], $array);
        } 
        break;
    }
}

The problem is that it adds only one item by replacing the previously added one. Each item has its ID which is sent by their button - GET method. What is the problem? Thanks.

You are merging the contents of array into the existing array called "cart_item". However, any key of an array can only exist once. so by merging another shopping car item, you are overriding the one already there.

You could handle it like this:

    if (isset($_SESSION["cart_item"])) {
       // make sure the cart_item key exists before adding anything to it.
       $_SESSION['cart_item'] = array();
       $_SESSION["cart_item"][] = $array;
    } 
    else {
       $_SESSION["cart_item"][] =  $array;
    } 

However, this means that you can add the same product twice. Since everything has their own ID, you could consider using $row['id] as the key for items.

why dont you push an item into the array instead of replacing it ?

replace this line (and make the same for below code in the else)

$_SESSION["cart_item"] = $array;

by

$_SESSION["cart_item"][$j] = $array;

or better:

$_SESSION['cart'][$j] = $array;

Make sure you define $_SESSION['cart'] somewhere near the start of the session

make the cart stored in session be a string, with elements separated by a character like ';' and those elements could themselves be lists separated by a different character like ','.

The session/cookie would look like:

<id>,<seller>,<name>,<CPU>,<price>,<img>;
<id>,<seller>,<name>,<CPU>,<price>,<img>;
<id>,<seller>,<name>,<CPU>,<price>,<img>

This means that you could split the string with ";" and then every element in that array with ",".

To implement this you would switch this:

$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"], $array);

for this:

$_SESSION["cart_item"] .= $row["seller"] . "," . $row["CPU"] . "," //and so on

Also, be carefull with sql_injection. You can change the "id_" parameter to a SQL query and damage you database.

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