简体   繁体   中英

Auto increment a SESSION key ID

I'm having a problem in doing something.
I have this code snippet to add a product to cart:

$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "";
$product_name = isset($_GET['product_name']) ? $_GET['product_name'] : "";

$sql = "SELECT * FROM products WHERE product_id LIKE '{$product_id}' AND product_name LIKE '{$product_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();

$num = $stmt->rowCount();

if($num == 1)
{
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        extract($row);
        if(!isset($_SESSION['cart']))
        {
            $product_id_session = 1;
        }
        else
        {
            $count = count($_SESSION['cart']); 
            $product_id_session = $count++;
        }

        $columns = array
        (
            'product_id_session' => $product_id_session,
            'product_id' => $product_id,
            'product_name' => $product_name,
            'product_price' => $product_price           
        );
        $_SESSION['cart'][$product_id_session] = $columns;      
        redirect_to('products.php?&message=added&product_name='. $_SESSION['cart'][$product_id_session]['product_name']);
    }
}

As you can see, if the session cart is created, I assign the variable $product_id_session with the count of SESSION arrays plus one. Otherwise, the variable $product_id_session is set to 1 . In the cart page I have a link to remove the selected product:

foreach($_SESSION['cart'] as $product)
{
    echo "<button onClick=\"location.href='remove.php?product_id_session={$product['product_id_session']}'\">
    Remove from cart
    </button>";
}

Then, in the file I have this to process the data from Query String and remove the product from the cart: 文件中,我可以使用它来处理查询字符串中的数据并从购物车中删除产品:

$product_id_session = isset($_GET['product_id_session']) ? $_GET['product_id_session'] : "";
unset($_SESSION['cart'][$product_id_session]);

The problem I'm facing is: for example, I added two products in the cart. Then I removed the first product and added another product to the cart. The new product, instead of being added, just will replace the product that was previously added in the cart and the $product_id_session will be always the same value. What I'm doing wrong? How to specify an ID for the SESSION?

You can add new items to the cart just with:

$_SESSION['cart'][] = $columns;

Then it will be appended to end of the array.

And, after deleting item from the array, you can (but it is not necessary) re-index it by

$_SESSION['cart'] = array_values($_SESSION['cart']);

When printing out the cart, you just update the foreach loop to catch the key value into some variable, ie $index. The difference is in the $index=>$product part.

foreach($_SESSION['cart'] as $index=>$product)
{
    echo "<button onClick=\"location.href='remove.php?product_id_session={$index}'\">
    Remove from cart
    </button>";
}

Remove.php remains basically the same, I just updated it for better readibility:

if (isset($_GET['product_id_session']) and $_GET['product_id_session']) {
    $product_id_session = $_GET['product_id_session'];
    unset($_SESSION['cart'][$product_id_session]);
}

Instead of trying to create an extra ID to manage your cart you should just rely on the unique product ID already stored in your database :

if($num == 1) {
    $row = $stmt->fetch(PDO::FETCH_ASSOC); // no need for the loop as you only have 1 result
    extract($row);
    if(!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
    }
    // keep track of the added product for the time being
    if (!isset($_SESSION['cart'][$product_id])) {
        $columns = array(
            'product_id_session' => $product_id_session,
            'product_id' => $product_id,
            'product_name' => $product_name,
            'product_price' => $product_price,
            'amount' => 0, //just add last comma as good practise here
        );
        $_SESSION['cart'][$product_id] = $columns;
    }
    //raise the amount
    $_SESSION['cart'][$product_id]['amount']++;
    redirect_to('products.php?&message=added&product_name='. $_SESSION['cart'][$product_id_session]['product_name']);
}

And change the remove accordingly :

foreach($_SESSION['cart'] as $product) {
    echo "<button onClick=\"location.href='remove.php?product_id={$product['product_id']}'\">Remove from cart</button>";
}

EDIT :

To keep an "unique" id you should not use count to calculate the ID Just use an extra variable to keep track of last Id :

    if(!isset($_SESSION['cart']))
    {
        $_SESSION['cart'] = array();
        $_SERVER['cart_product_id'] = 1;
    }
    else
    {
        $_SERVER['cart_product_id']++;
        $product_id_session = $_SERVER['cart_product_id'];
    }

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