I'm trying to get data from multiple tables in MySQL (The tables include option data for each item available to buy on my ecommerce site). The values are being pulled from a shopping cart session as follows:
foreach($_SESSION['cart'] as $id => $data)
{
// Calulate total for each item
$subtotal = $data['quantity'] * $data['price'];
$total += $subtotal;
// This gets the Cart sessions unique ID, so I can get the options from the database using it!
$sessionidforoptions = $data['uniquesessid'];
//Out put shopping cart data
echo "TABLE ROWS WITH EACH ITEM GO HERE (Product, Qty, Price for item etc...";
I then use the $sessionidforoptions value to get the options from the database:
// Get options IDs from Database
foreach($_SESSION['sessionoptions'][$sessionidforoptions] as $id2 => $data2) { $$id2 = $data2; }
if (isset($option1) && ($option1 != "")) { $list = $option1; }
if (isset($option2) && ($option2 != "")) { $list .= ",".$option2; }
if (isset($option3) && ($option2 != "")) { $list .= ",".$option3; }
// Query Database
$optionsquerysql = "SELECT * from productOptions WHERE productOptionsID IN ('". $list ."')";
$optionsresultsql= mysql_query($optionsquerysql) or die(mysql_error());
Then output the options:
while ($optionssql = mysql_fetch_array($optionsresultsql)) {
$optionNamesID = $optionssql["optionNamesID"];
$optionValue = $optionssql["optionValue"];
// Get option names from databsae
$optionsnamesquerysql = "SELECT * from optionNames WHERE optionNamesID = ".$optionNamesID."";
$optionsnamesresultsql= mysql_query($optionsnamesquerysql) or die(mysql_error());
//Output options names + options
while ($optionnamessql = mysql_fetch_array($optionsnamesresultsql)) {
$optionName = $optionnamessql['optionName'];
echo $optionName.': '.$optionValue.'<br />';
}
}
This almost works! The session has 3 options stored for each item in the shopping cart (size, colour, etc)
I get the following:
Item 1 - £20.00 Size: Small
Item 2 - £22.00 Size: Medium
Item 3 - £45.00 Size: Large
This is what I should get:
Item 1 - £20.00 - Size: Small - Colour: Black - Belt: Small
Item 2 - £22.00 - Size: Medium - Colour: Blue - Belt: Medium
Item 3 - £45.00 Size: Large - Colour: Pink - Belt: Large
As you can see, the last while loop is only outputting the first option each time
while ($optionnamessql = mysql_fetch_array($optionsnamesresultsql)) { OPTION OUTPUT }
Should I be using foreach here instead of a while loop?
Really appreciate any advice anyone can offer. I realise my code isn't very clean. I'm still learning... I'm sorry about this.
Thanks for any advice you can offer