PHP arrays are not working in version 5.2.17

Hi Everyone,

I’m building a custom shopping cart. I’m having trouble getting my code to work on a production server that is running PHP version 5.2.17. My test machine is running version 5.3.0 and the code works just fine. I do not have the ability to upgrade the version of PHP on the production machine. Here is part of my code. If we can fix this, I can fix the other switch cases:

[php]

//this code adds the item to the cart and creates an array and session variable for the cart. The array is multidimensional (item id => quantity).

if (isset($_GET[“action”]))
{
$action = $_GET[“action”];
$id = $_GET[“id”] ;
$q = $_GET[“quantity”];
$cart = array();

switch ($action)
{
	case "add":
		if ($_SESSION["cart"])
		{				
			$cart = $_SESSION["cart"];
			if (array_key_exists($id,$cart))
			{
				$cart[$id] = $cart[$id] + $q;
			}
			else
			{	
				$cart[$id] = $q;
			}					
		}
		else
		{
			$cart[$id] = $q;
		}
		$_SESSION["cart"] = $cart;
		break;
}

}

//this code displays the cart array

if ($_SESSION[“cart”])
{
$cart = $_SESSION[“cart”];

foreach($cart as $key => $value)
{	
	$runQ1 = mysql_query("SELECT * FROM products WHERE id='$key'") or die(mysql_error());	
	$results = mysql_fetch_array($runQ1);
	print "<table><tr><td>$results[1]</td><td>$results[2]</td><td>$results[3]</td><td>$results[4]</td></tr></table>";
}

}
else
{
print “

There are no items in your shopping cart.
”;
}

[/php]

The cart session variable is being set but it is only holding one item at a time. If I add a second item to the cart, the 1st item disappears and only the second one is present in the session variable and the table. I’m not sure if it is a session problem or an array problem. Please help before I lose all of my hair! I don’t understand why this code works on php 5.3.0 and not 5.2.17…

Thanks in advance!

-Isaac

I am not sure how to fix problem (as I myself avoid storing arrays in a session variable), but as an option you can serialize $cart array before saving it to session variable, so that you store scalar value. Then use unserialize()

Thanks for your quick repsonse.

I tried serializing the cart array, then storing it into the session variable, then unserializing it but I get the following error:

  1. unserialize() expects parameter 1 to be string, array given

I guess unserialize() doesnt work with arrays. Any other suggestions?

It’s working now…I did a comparison between the php.ini files on my machine and the production server. I turned off ‘Register Globals’ in the php.ini file on the production server and now the cart is working perfectly! Thanks

Sponsor our Newsletter | Privacy Policy | Terms of Service