I have a small issue with sessions. I have built a small shopping cart-esque section on a site which does nearly what I want it to do. One issue is that when I visit my basket and have NO items in it, it throws up an error:
Warning: Invalid argument supplied for foreach() in /home/andydownham/site.com/wp-content/themes/theme/basket.php on line 28
I guess it needs something like 'if items are in cart' > use normal code > else display 'sorry there are no items in your cart' it’s just I don’t know how exactly how to implement this.
Here is the code I am using to store things into the session
<?php
session_start();
//var_dump($_POST);
//print_r($_SESSION);
$_SESSION['event_orders'][] = $_POST['event_id'];
?>
and this is the code I am using on the basket page:
<?php
session_start();
foreach($_SESSION['event_orders'] AS $event_id){
echo '<div class="grad basket">';
echo '<div class="thumb">';
$EM_Event = em_get_event($event_id);
echo $EM_Event->output('#_EVENTIMAGE{72,72}');
echo '</div>';
echo '<div class="basket-title"><h2>';
echo '<a href="';
$EM_Event = em_get_event($event_id);
echo $EM_Event->output('#_EVENTURL');
echo '">';
$EM_Event = em_get_event($event_id);
echo $EM_Event->output('#_EVENTNAME');
echo '</a>';
echo '</h2>';
echo '<div class="basket-dates"> Dates:';
$EM_Event = em_get_event($event_id);
echo $EM_Event->output('#_EVENTDATES');
echo '</div></div>';
echo '<div class="klear"></div>';
echo '<input type="submit" class="remove" value="remove" />';
echo '</div>';
echo '<br/>';
}
?>
You need to make sure that
$_SESSION['event_orders']exists (even if it’s an empty array). You can check that with the empty function (which will catch the empty array as well):You need to be careful with
empty, though. These things are also considered “empty” (from the manual):Especially note that the string containing “0” is considered empty! That means that if you, in the future somewhere, have a HTML form where the user may input values and the user puts in the number
0, that field will be considered “empty” by this function. That is not always what you want. In this case, though, it is useful for checking the “emptiness” of your array.