• Notice regarding image hosts and attachments. See here.

PHP Array Problem

Associate
Joined
16 Aug 2004
Posts
268
I'm trying to store an ID and Product Name into a session to be used as a shopping basket but my code is writing over the information it already has in the while loop. I think I need to use a nested array but not sure.

Can anyone point me in the right direction on what I should be searching for to learn how to fix my problem

Code:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{			
	$cart_array = array('id' => "{$row['id']}", 'name' => "{$row['product_name']}");
	$_SESSION['cart'] = $cart_array;		
}		
foreach($_SESSION['cart'] as $key=>$value)
{
	echo $value . ' <br />';
}
 
Correct, you're assigning on each loop. It should be something like

Code:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{			
	$cart_array = array('id' => $row['id'], 'name' => $row['product_name']);
	$_SESSION['cart'][] = $cart_array; // Just an example showing how to append the new array
}

depending on how you want the array structured.
 
Thanks for that psyr33n,

It now seems to be adding the extra products but it is just storing the word "array" over and over again instead of the product name. I had the same problem before, do you have to echo a nested array in a special way?
 
Back
Top Bottom