Home > Back-end >  PHP code for cart.php - cart is always empty
PHP code for cart.php - cart is always empty

Time:01-30

I have these two codes for product.php and cart.php...

`Product.php:
<?php

session_start();
if (!isset($_SESSION['user'])) {
  header('Location: login.php');
  exit;
}

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

require 'db.inc.php';


if (!isset($_GET['id'])) {
    header('Location: store.php');
    exit;
}


$product = findProductById($_GET['id']);

$features = findProductFeaturesById($_GET['id']);

if (isset($_POST['submit'])) {
    $id = $_POST['product_id'];
    $quantity = $_POST['quantity'];
}


if (!$product) {
    header('Location: store.php');
    exit;
}

?>
<!doctype html>
<html lang="fr">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Lab 3">
    <meta name="author" content="">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6 fzT" crossorigin="anonymous">
</head>

<body >


    <header >
        <a href="/" >
            <svg  width="40" height="32" role="img" aria-label="Bootstrap">
                <use xlink:href="#bootstrap"></use>
            </svg>
        </a>

        <ul >
            <li><a href="store.php" >Le catalogue</a></li>
            <li><a href="cart.php" >Mes achats</a></li>
        </ul>

        <div >
            <a  href="logout.php" role="button">Quitter</a>
        </div>
    </header>

    <main >
        <nav aria-label="breadcrumb">
            <ol >
                <li ><a href="store.php">Catalogue complet</a></li>
                <li  aria-current="page"><?= $product->short_name ?></li>
            </ol>
        </nav>
        <div >
            <div  style="width: 36rem;">
                <div >
                    <div >
                        <h1><?= $product->name ?></h1>
                    </div>
                    <div >
                        <?= $product->price ?>$
                    </div>
                </div>
            </div>
            <div >
            </div>
            <div >
                <p ><?= $product->available_quantity ?> en stock</p>
            </div>
        </div>
       
        <h2>A propos de cet article</h2>
        <ul>

      
        
        <?php
        // Rajout des caractéristiques à partir de la fonction findProductFeaturesById //
        $features = findProductFeaturesById($product->id);
        foreach ($features as $feature) {
            echo '<li>' . $feature['feature'] . '</li>';
        }
    ?>
        </ul>
        <form action="cart.php" method="post">
    <input type="hidden" name="product_id" value="<?=$product->id?>">
    <label for="quantity">Quantité:</label>
    <input type="number" name="quantity" value="1" min="1" max="<?=$product->available_quantity?>">
    <input type="submit" value="Ajouter au panier">
    <?php
    if (isset($_POST['submit'])) {
    $id = $_POST['product_id'];
    $quantity = $_POST['quantity'];
    addProductToCart($id, $quantity);
    header('Location: cart.php');
    exit;
}
?>
</form>

    </main>

</body>

</html>

cart.php:

<?php

session_start();

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

require 'db.inc.php';

if (isset($_POST['submit'])) {
    $product_id = $_POST['product_id'];
    $quantity = $_POST['quantity'];

    if (!isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id] = array(
            'product_id' => $product_id,
            'quantity' => $quantity
        );
    } else {
        $_SESSION['cart'][$product_id]['quantity']  = $quantity;
    }
}

if (isset($_POST['update'])) {
    $product_id = $_POST['product_id'];
    $quantity = $_POST['quantity'];

    if (!isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id] = array(
            'product_id' => $product_id,
            'quantity' => $quantity
        );
    } else {
        $_SESSION['cart'][$product_id]['quantity'] = $quantity;
    }
}

foreach ($_SESSION['cart'] as $item) {
    $product = findProductById($item['product_id']);
    $product->quantity = $item['quantity'];
    $products[] = $product;
}

$cart = $_SESSION['cart'];

function addProductToCart($id, $quantity)
{
    if (isset($_SESSION['cart'][$id])) {
        $_SESSION['cart'][$id]['quantity']  = $quantity;
    } else {
        $_SESSION['cart'][$id] = array(
            'product_id' => $id,
            'quantity' => $quantity
        );
    }
}

// lorsque la quantité est 0, le produit est retiré du panier
function updateProductQuantity($id, $quantity)
{
    if ($quantity == 0) {
        unset($_SESSION['cart'][$id]);
    } else {
        $_SESSION['cart'][$id]['quantity'] = $quantity;
    }
}

?>
<!doctype html>
<html lang="fr">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Lab 4">
    <meta name="author" content="">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6 fzT" crossorigin="anonymous">
</head>

<body >


    <header >
        <a href="/" >
            <svg  width="40" height="32" role="img" aria-label="Bootstrap">
                <use xlink:href="#bootstrap"></use>
            </svg>
        </a>

        <ul >
            <li><a href="store.php" >Le catalogue</a></li>
            <li><a href="#" >Vos achats</a></li>
            <li><a href="orders.php" >Vos commandes</a></li>
        </ul>

        <div >
            <a  href="logout.php" role="button">Quitter</a>
        </div>
    </header>

    <main >
        <h1>Votre panier</h1>
        <?php if (count($_SESSION['cart']) != 0) :?>
        <div >
            <?php foreach ($cart as $id => $quantity) : 
                    $product = findProductById($id);
            ?>
                <div >
                <form method="POST" id="update_cart_form" action="cart.php">
  <input type="hidden" name="id" value="<?= $id ?>">
  <h2><?= $product->short_name ?></h2>
  <label for="quantity" >Quantité :</label>
  <input type="number"  id="quantity" name="quantity" value="<?= $quantity ?>">
  <button type="submit" >Mettre à jour</button>
  <button type="submit" >Supprimer</button>
</form>
                </div>
            <?php endforeach; ?>
        </div>
        
        <form method="POST" id="pay_cart_form" action="orders.php">
            <button type="submit"  name="action" value="pay_cart">Payer maintenant</button>
        </form>

        <?php else :?>
        <p>Votre panier est vide!</p>
        <?php endif;?>
        
    </main>
</body>

</html>`

I tried to change the code many times, but at the end the cart array is always empty... i dont understand why?

I tried to change the code to make sure i POST quantity and id to display the right product with quantity, but the cart stays empty.

CodePudding user response:

It looks like PHP is not persisting your session even though it is being created, which will always return the initial value as the default value.

First, you must check if the cookie is being created on the browser. Open the developer inspection tool, go to Cookie Storage and see if there is a session cookie, by default its name is PHPSESSID.

If a cookie is not being created, you must check session.save_path configuration in your php.ini file. Your PHP must not have the permissions for writing and creating sessions.

However, if a cookie is being created, run the code below on your host:

<?php

session_start();

if (!isset($_SESSION['counter'])) {
    $_SESSION['counter'] = 0;
}

$_SESSION['counter']  ;
echo 'Counter: '.$_SESSION['counter'];

If the counter is not incremented, the PHP creates a session but it's not saving it. You must check if there are any errors related to sessions in the error logs, pointing to an invalid configuration or misspelled configuration.

At this point, if the counter is working but your $_SESSION['cart'] is not being updated, try to do the following:

  • Make sure session_start() is running on top of your code three, before any other code ran;
  • Make sure that the same session ID is used when refreshing pages, and changing pages;
  • Try to isolate the problem by breaking your code and executing it step by step on browser.

EDIT 1

  • Sometimes when redirecting to another location with the header() method, the session data can be not saved before the header is sent. The natural fix is constructing a better code. Try to use the session_write_close() method before sending the new header.

CodePudding user response:

It doesnt seem to correct the problem... you can see it in my website if you want: http://samibegah-php.atwebpages.com/lab4/login.php you can use username: Jean password: 1234

  •  Tags:  
  • php
  • Related