【发布时间】:2011-02-28 21:23:36
【问题描述】:
我正在尝试从 MySQL 中的多个表中获取数据(这些表包括可在我的电子商务网站上购买的每件商品的选项数据)。从购物车会话中提取的值如下:
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...";
然后我使用 $sessionidforoptions 值从数据库中获取选项:
// 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());
然后输出选项:
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 />';
}
}
这几乎行得通!该会话为购物车中的每个项目存储了 3 个选项(尺寸、颜色等)
我得到以下信息:
项目 1 - £20.00 尺寸:小号
商品 2 - £22.00 尺寸:中号
第 3 项 - £45.00 尺寸:大号
这是我应该得到的:
项目 1 - 20.00 英镑 - 尺寸:小号 - 颜色:黑色 - 腰带:小号
商品 2 - 22.00 英镑 - 尺寸:中号 - 颜色:蓝色 - 腰带:中号
商品 3 - £45.00 尺寸:大号 - 颜色:粉色 - 腰带:大号
如你所见,最后一个while循环每次只输出第一个选项
while ($optionnamessql = mysql_fetch_array($optionsnamesresultsql)) { OPTION OUTPUT }
我应该在这里使用 foreach 而不是 while 循环吗?
非常感谢任何人提供的任何建议。我意识到我的代码不是很干净。我还在学习……对此我很抱歉。
感谢您提供的任何建议
【问题讨论】:
标签: php mysql foreach while-loop