Hello, I'll explain this real quick. I'm building a php shopping cart and have stored the orders people make in a session where the id of the product ($id) is followed by the amount they order ($aantal). I now want to display the content of my cart using the following code (I'm using Smarty btw) and have to fetch the result from a database. foreach($_SESSION['cart'] as $id => $aantal) { $sql = "SELECT lps.titel FROM lps WHERE id = ".$id; $result = mysql_query($sql); if ($result) { $data = array (); while ($row = mysql_fetch_assoc($result)) { $data[] = $row; } } echo "<pre>"; print_r($data); echo "</pre>"; } $smarty->assign ("cartContent", $data); PHP: Normally I should be able to send the $data to my html page using the smarty assign and use something like {$cartContent.titel} to show the title in this example but this won't work because something is wrong with one of the loops. When printing this out on the page I get the following result: If anyone can help me I would certainly leave a +! Kinds regards.
This line re-initializes the $data array on each iteration of the loop: $data = array (); PHP: If you'd like $data to store all of the results, you'll need to move that line to the top before the foreach loop.
Damn what a stupid mistake of me! I almost have what I need, now it's giving me the array but adding a title to the array one at a time giving me too much results. I know this is because of the line $data[] = $row but i have no idea how to fix this without removing one of the loops?
It is because $row is an array after you use mysql_fetch_assoc so you are just creating new arrays within your $data array. Try the following and I've also corrected the if ($result) which should really be if (mysql_numrows($result)). Please see updated code: foreach($_SESSION['cart'] as $id => $aantal) { $sql = "SELECT lps.titel FROM lps WHERE id = ".$id; $result = mysql_query($sql) or die(mysql_error()); if (mysql_numrows($result)) { $data = array (); while ($row = mysql_fetch_object($result)) { $data[] = $row->titel; } } echo "<pre>"; print_r($data); echo "</pre>"; } $smarty->assign ("cartContent", $data);
funny. because you have two loops! maybe you can do like this $ids = array_keys($_SESSION['cart']); $sql = "SELECT lps.titel FROM lps WHERE id in( ". implode(',', $ids) . ")"; $result = mysql_query($sql); if ($result) { $data = array (); while ($row = mysql_fetch_assoc($result)) { $data[] = $row; } } echo "<pre>"; print_r($data); echo "</pre>"; PHP:
Thank you for your help (all of you), really appreciate it! Using the solutions suggested by Qc4 and adamsinfo I was able to fix my problem... Thanks for your code too gapz101, your solutions looks less complicated then the 2 loops I'm using, I'll keep that in mind ;-)!