Jump to content
jimleeder123

Auto incremented sessions

Recommended Posts

I've got a session $_SESSION['product'.$i.''] that I am trying to echo out. The auto increment on it is working, the $i is auto incremented.

 

So if I do:

 

$i = $_SESSION['count'];

 

echo $_SESSION['product'.$i.''];

echo " (";

echo $_SESSION['count'];

echo ") ";

 

It will come up as "Ham Pizza (4)" if it is the 4th time I have done the process and so on.

 

If I echo the sessions out like below:

 

echo $_SESSION['product1'];

echo $_SESSION['product2'];

echo $_SESSION['product3'];

 

It will come out with the associated product names in the order I done them, eg:

 

Ham PizzaMargheritaBBQ Pizza

 

What I want to know is how to echo them all out at the same time. This is so a user can see what is in their cart, and when I get to it, the checkout too.

 

Any help please?

Share this post


Link to post
Share on other sites

Just add your products into an array, say $_SESSION['products'].

$_SESSION['products'][] = 'Ham pizza';
$_SESSION['products'][] = 'Margherita';
$_SESSION['products'][] = 'BBQ Chicken';

echo count($_SESSION['products']) . 'Items<br>';

foreach ($_SESSION['products'] as $item) {
    echo "$item<br>";
}

Share this post


Link to post
Share on other sites

No, that won't work. Products are shown each with an "add to cart" button, which then takes you to a process page which sets the product name to the auto incremented session - $_SESSION['product'.$i.'']; - which is then echoed out on the cart section of the website (all pages).

 

Sessions will be stored as echo $_SESSION['product1']; echo $_SESSION['product2']; echo $_SESSION['product3']; and so on.

 

Instead of echoing echo $_SESSION['product'.$i.''] I want some code to be able to echo all of these at the same time if they are set.

Share this post


Link to post
Share on other sites

You're missing the point. If you use arrays you can do everything you just said, except you're not fighting against PHP the whole time.

Share this post


Link to post
Share on other sites

There could be over 10 sessions at a time, depending on what the user wants to order. Will I have to write out all the product names into an array like above? The auto increment value ( $i ) is the number for how many items are in the cart, so if its the 5th item in the cart then $i will be 5.

Share this post


Link to post
Share on other sites

I have tried the array suggested and it works, but whenever you click onto another page, it echoes the session a second time, third if you go to another page and so on.

 

I tried unsetting the session after the for each loop but that clears the older item in the cart and just shows the item just entered.

Share this post


Link to post
Share on other sites

$_SESSION['products'][] = $_SESSION['product'.$i.''];
 

foreach ($_SESSION['products'] as $item) {
echo "$item<br>";
}

 

The session $_SESSION['product'.$i.''] is the product that has just been processed

Share this post


Link to post
Share on other sites

I have noticed that if I remove the underscore in $_SESSION['product'.$i.''] it only gets echoed once but the count still goes up

Share this post


Link to post
Share on other sites

Here's a simple example using an array as suggested

<?php
session_start();
if (!isset($_SESSION['products'])) {
    $_SESSION['products'] = [];
}

$menu = [   1 => "Ham and Pineapple Pizza",
            2 => "Margherita",
            3 => "BBQ Chicken",
            4 => "Lamb Kebab",
            5 => "Beef Burger",
            6 => "Hot Dog"       ];

$order = '';           
if (isset($_GET['product'])) {
    $_SESSION['products'][] = $menu[$_GET['product']];
}
elseif (isset($_GET['view'])) {
    $order = "<ol>\n";
    foreach ($_SESSION['products'] as $item) {
        $order .= "<li>$item</li>\n";
    }
    $order .= "</ol>\n";
}

?>
<html>
<head>
<style type="text/css">
#cart {
    border: 1px solid gray;
    background-color: #C0FFC0;
    padding: 10px;
}
</style>
</head>
<body>
<h1>Menu</h1>
    <?php
        foreach ($menu as $key=>$item) {
            echo "<p>$item <a href='?product=$key'>Order item</a></p>";
        }
    ?>
<div id='cart'>
    Items ordered: <?= count($_SESSION['products'])?> items. (<a href='?view=1'>View</a>)
    <?=$order?>
</div>
</body>
</html>

Share this post


Link to post
Share on other sites

Thats just echoing out all items in the array regardless. I want to echo out product names selected by the user, as saved in $_SESSION['product'.$i.''];

Share this post


Link to post
Share on other sites

Of course it echoes all items in the menu regardless - so you can place an order.

 

When you view the order it only echoes those that have been selected by the user (ie those in the $_SESSION['products'] array)

Share this post


Link to post
Share on other sites

I have got it working on my end but I need the price and product name going through together as one, currently they are treated as two seperate array items.

 

I have the name and price assigned to their own variables ($name and $price). Could I put these two variables together or is it not possible? I have been trying things like "$together = $name && $price" but of course doesn't work.

Share this post


Link to post
Share on other sites

Just one other way of maybe approaching the problem .... when the user logs in, or starts to fill up a cart, the PHP code generates a "session ID"  (think up your own unique way to do this, for example it could be some combination of the login time and the IP address .. or whatever, just use your creativity).

 

Then every time somebody adds something to the cart, you write into a database, using the session ID as a reference.  That way, you only need one session variable. At the end, when they want to sum up and pay, just list all the items in the database stored against that session ID

Share this post


Link to post
Share on other sites

I'd store the prices in the "$menu" array so that it is effectively the database.

<?php
session_start();
if (!isset($_SESSION['products'])) {
    $_SESSION['products'] = [];
}

$menu = [   1 => ['name' => "Ham and Pineapple Pizza", 'price' => 3.49],
            2 => ['name' => "Margherita", 'price' => 3.49], 
            3 => ['name' => "BBQ Chicken", 'price' => 2.99],
            4 => ['name' => "Lamb Kebab", 'price' => 2.49],
            5 => ['name' => "Beef Burger", 'price' => 2.49],
            6 => ['name' => "Hot Dog", 'price' => 1.99]       ];

$order = '';
$orderTotal  = 0;           
if (isset($_GET['product'])) {
    $_SESSION['products'][] =$_GET['product'];
}
elseif (isset($_GET['view'])) {
    $order = "<ol>\n";
    foreach ($_SESSION['products'] as $item) {
        $order .= "<li>{$menu[$item]['name']} ({$menu[$item]['price']})</li>\n";
        $orderTotal += $menu[$item]['price'];
    }
    $order .= "</ol>\n";
    if ($orderTotal) {
        $order .= sprintf("Total price: %6.2f<br>", $orderTotal);
    }
}
elseif (isset($_GET['cancel'])) {
    $_SESSION['products'] = [];
}
?>
<html>
<head>
<style type="text/css">
#cart {
    border: 1px solid gray;
    background-color: #C0FFC0;
    padding: 10px;
}
</style>
</head>
<body>
<h1>Menu</h1>
    <table>
    <?php
        foreach ($menu as $key=>$item) {
            echo "<tr><td>{$item['name']}</td>
                 <td>{$item['price']}</td>
                 <td><a href='?product=$key'>Order item</a></td></tr>";
        }
    ?>
    </table>
<div id='cart'>
    Items ordered: <?= count($_SESSION['products'])?> items. [<a href='?view=1'>View</a>] 
    <?=$order?>
    <br>
    [<a href='?cancel=1'>Cancel order</a>]
</div>
</body>
</html>
Edited by Barand
  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.