[英]Adding item to shopping cart using php and html
我正在嘗試使用php和html來實現購物車。 我遇到的問題是使用會話存儲要存儲的產品的ID。 以下是我目前擁有的代碼:
<?php
session_start();
?>
//There are three HTML Forms that take and display input, and output.
<?php
$_SESSION['cart'] = array();
if(isset($_GET['search'])){
echo "<table border=1>";
echo "<th>Product Image</th>";
echo "<th>Product Name</th>";
echo "<th>Price</th>";
foreach($xml->categories->category->items->product as $product){
$imageURL = $product->images->image[0]->sourceURL;
$id = $product['id'];
echo "<tr>";
echo "<td><a href= 'buy.php?buy=".$id."'><img src=".$imageURL."></img></a></td>";
echo "<td>".$product->name."</td>";
echo "<td>".'$'.$product->minPrice."</td>";
}
}
if(isset($_GET['buy'])){
$product_id = $_GET['buy'];
if(isset($_SESSION['cart'])){
array_push($_SESSION['cart'],$product_id);
}
}
print_r ($_SESSION);
?>
第一個if語句的作用是獲取搜索詞並獲取最接近的結果。 然后顯示圖像,名稱和價格。 當您單擊圖像時,會有一個href,並且應該將其添加到購物車中。 那就是第二個if語句起作用的地方。 如果單擊了圖像,我想獲取ID並將其存儲在會話中。 單擊時,它將存儲產品的ID,但是當我返回添加其他商品時,以前的ID將替換為新ID。 有人可以向我解釋我哪里出錯了嗎? 任何幫助將不勝感激。
您的問題在以下行中:$ _SESSION ['cart'] = array();
像這樣檢查:
if(empty($_SESSION['cart']))
$_SESSION['cart'] = array();
那應該解決
首先,您必須為$ _SESSION ['cart']分配一個數組。 否則,它將僅存儲單個值。
$ids = array();
$_SESSION['cart'] = $ids;
然后它將起作用。
您必須使用數組來存儲多個值:
$shop_array= array(); // this is create the array with the name shop_array
// now create the session and assign the shop_array to creating session
$_session['mycart'] = $shop_array;
您可以使用print_r()
函數檢查存儲的值:
print_r($_session['mycart']);
您將獲得存儲ID的結果集。
你能試試看嗎
if(isset($_GET['buy'])){
$product_id = $_GET['buy'];
if(!in_array($product_id, $_SESSION['cart'])){
$_SESSION['cart'][]=$product_id;
}
}
您必須選擇存儲購物車-我個人更喜歡會話和cookie,請嘗試使用此代碼在會話中存儲購物車
if(isset($_POST['item_src']))
{
$_SESSION['name'][]=$_POST['item_name'];
$_SESSION['price'][]=$_POST['item_price'];
$_SESSION['src'][]=$_POST['item_src'];
echo count($_SESSION['name']);
exit();
}
在此處創建添加到購物車系統的完整教程http://talkerscode.com/webtricks/simple-add-to-cart-system-using-jquery-ajax-and-php.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.