因此,讓我先描述一下我在做什麼。我正在製作一個購物車,可以選擇物品。這些項目及其各自選擇的選項會存儲在會話中並顯示在購物車中以供客戶驗證。PHP中的錯誤對於每個字符串
我有三套代碼來向您展示:
首先爲了使複選框選項的代碼(位於根/配置/模板/產品details.php)
<?php foreach($options as $option): ?> <input type="checkbox" name="candies[]" value="<?php echo $option['candy_name']; ?>" /><?php echo $option['candy_name']; ?><br/> <?php endforeach; ?>
其次爲項目和選項同時設置會議代碼:(位於根/配置/車/ cart.php
$optionsSelected = array(); if(!empty($_GET['candies'])){ foreach($_GET['candies'] as $options){ $optionsSelected[] = $options; } } case "add": $_SESSION['cart'][$product_id]++; $_SESSION[$product_id] = $optionsSelected; header('location: ../../cart.html'); break;
注意這行代碼:$_SESSION[$product_id] = $optionsSelected;
最後顯示在購物車中的選項:(位於根/配置/模板/購物-cart.php)
<?php foreach($_SESSION[$product_id] as $options): ?> <?php echo $options; ?> <?php endforeach; ?>
當我完成所有設置後,我選擇我想要的選項並將產品添加到購物車。我得到的購物-cart.php頁面上此錯誤:
Warning: Invalid argument supplied for foreach() ...
但如果我把購物-cart.php代碼cart.php頁面內並註釋掉頭(「」);一切都正確,並且工作非常好。所以在cart.php頁面和shopping-cart.php頁面之間有些問題。但我無法弄清楚它是什麼。任何幫助,建議,想法,解決方案將是美好的,非常感謝!先謝謝你。
爲了更好地理解這個問題,下面是一個shopping-cart.php頁面的圖片。
UPDATE
我相信問題是root/config/cart/cart.php
頁面和頁面root/config/templates/shopping-cart.php
之間。這裏是兩個完整的代碼。
根/配置/車/ cart.php代碼:
<?php session_start(); require '../config.php'; $product_id = $_GET['id']; $action = $_GET['action']; $optionsSelected = array(); if(!empty($_GET['candies'])){ foreach($_GET['candies'] as $options){ $optionsSelected[] = $options; } } function productExists($product_id) { require '../config.php'; $stmt = $db->prepare("SELECT * FROM products WHERE id=$product_id"); $stmt->execute(array($id, $name)); $row_count = $stmt->rowCount(); } if($product_id && $row_count < 0) { die("Error. Product Doesn't Exist"); } switch($action) { case "add": $_SESSION['cart'][$product_id]++; $_SESSION[$product_id] = $optionsSelected; session_write_close(); header('location: ../../cart.html'); break; case "remove": $_SESSION['cart'][$product_id]--; if($_SESSION['cart'][$product_id] == 0) { unset($_SESSION['cart'][$product_id]); header('location: ../../cart.html'); } header('location: ../../cart.html'); break; case "empty": unset($_SESSION['cart']); break; } ?>
'$ product_id'從哪裏來? – Jompper
我忘了補充一點,對不起。它來自:''product_id = $ _GET ['id'];'在root/config/cart/cart.php頁面上'' –
你看到你將用戶重定向到cart.html,並且沒有針對id的GET。仍然有foreach($ _ SESSION [$ product_id]' – Jompper