我目前正在为一个网站创建一个购物篮,但是如果我回应我拥有的每个产品以及当前购物篮中的产品数量以及其他产品,我现在只能让它工作。但是在数据库中它不显示数字。我正在尝试创建一个foreach循环,然后回显篮子中每个项目的结果而不是我的所有产品。以下是我的代码以及它在我的网站上的外观。我尝试创建foreach循环的所有努力似乎都会导致foreach循环导致整个脚本失败。任何有关这个问题的帮助将非常感谢!
if ($_GET[action]=="add") {
$id=$_GET['radio_id'];
$_SESSION['basket'.$id]++;
echo "You currently have $_SESSION[basket1] Grundig G3 in your basket<br />";
echo "You currently have $_SESSION[basket2] Eton E5 in your basket<br />";
echo "You currently have $_SESSION[basket3] Eton E1 G3 in your basket<br />";
echo "You currently have $_SESSION[basket4] Morphy Richards DRM Radio G3 in your basket<br />";
echo "You currently have $_SESSION[basket5] TechniSat MultyRadio in your basket<br />";
echo "You currently have $_SESSION[basket6] Sony ICF-SW7600GR in your basket<br />";
echo "You currently have $_SESSION[basket7] Sony AN-LP1 in your basket<br />";
}
else {
echo "You have no items in your shopping cart.";
}
网站显示这个,当我添加一个项目时,它会显示一个数字或增加一个数字,具体取决于我添加到购物篮中的项目。
您目前在购物篮中有2个Grundig G3
您目前在购物篮中有1个Eton E5
您目前在购物篮中有Eton E1 G3
您目前在购物篮中有Morphy Richards DRM Radio G3
您目前在购物篮中有TechniSat MultyRadio
您目前在购物篮中有索尼ICF-SW7600GR
您目前在购物篮中有索尼AN-LP1
$result = mysqli_query($link, "SELECT * FROM radios WHERE radio_id=".$_GET[radio_id]) or die( mysqli_error($link));
$array = mysqli_fetch_array($result);
if ($_GET[action]=="add") {
$id=$_GET['radio_id'];
$_SESSION['basket'.$id]++;
$manufacturer=$array['manufacturer'];
foreach($_SESSION as $id => $amount){
if(strstr($id,'basket')){
echo "You have $amount $manufacturer in your basket.<br>";
}
}
@vascowhite
答案 0 :(得分:0)
如果没有其他代码写的:
$_SESSION[basket1]
在索引周围没有括号,因此它会尝试将该basket1渲染为常量。
答案 1 :(得分:0)
您正在寻找foreach()
loop,例如: -
$_SESSION['basket1'] = 2;
$_SESSION['basket2'] = 4;
$_SESSION['basket3'] = 10;
$_SESSION['someothervalue'] = 'test';
var_dump($_SESSION);
显然以上所有内容都只是测试代码。 foreach($ _ SESSION为$ key =&gt; $ amount){
if(strstr($key, 'basket')){
echo "You have $amount whatevers in your basket.<br>" . PHP_EOL;
}
}
输出: -
array (size=4)
'basket1' => int 2
'basket2' => int 4
'basket3' => int 10
'someothervalue' => string 'test' (length=4)
You have 2 whatevers in your basket.
You have 4 whatevers in your basket.
You have 10 whatevers in your basket.