[英]easy PHP shopping cart
我正在嘗試使用會話在php中制作購物車。 我遇到了麻煩,因此當您將多個商品添加到購物車時,它將顯示所有添加到購物車的商品。 到目前為止,我已經擁有了它,因此購物車中只能有一件東西,而當您離開頁面或添加其他項目時,最后一個項目將被覆蓋。 我知道我必須添加一個會話,例如$ _SESSION ['cart'],並在打印輸出信息時將其保存在其中,但是我不確定該怎么做。 任何幫助,將不勝感激。
$prodid=$_GET['pid'];
$quan=$_GET['quantity'];
$query="select * from Products where ProductID = '$prodid'";
$result=mysql_query($query);
$numOfRows=mysql_numrows($result);
for($i=0;$i<$numOfRows;$i++)
{
$productID=mysql_result($result, $i, "ProductID");
$prodTitle=mysql_result($result, $i, "Title");
$prodAuthor=mysql_result($result, $i, "Author1");
$prodPrice=mysql_result($result, $i, "Price");
Print"<h4>ID: $productID \n </h4>";
Print"<h4>Title: $prodTitle \n </h4>";
Print"<h4>Author: $prodAuthor \n </h4>";
Print"<h4>Price: $ $prodPrice \n </h4>";
}
編輯:
$prodid=$_GET['pid'];
$quan=$_GET['quantity'];
Print"$prodid";
Print"<br/>";
Print"$quan";
$query="select * from Products where ProductID = '$prodid'";
$result=mysql_query($query);
$numOfRows=mysql_numrows($result);
for($i=0;$i<$numOfRows;$i++)
{
$productID=mysql_result($result, $i, "ProductID");
$prodTitle=mysql_result($result, $i, "Title");
$prodPrice=mysql_result($result, $i, "Price");
}
$arr = array(
['id'] => "$productID",
['title'] => "$prodTitle",
['count'] => "$quan",
['price'] => "$prodPrice"
);
echo "id is " . $arr['id'];
您可以簡單地形成一個數組,其中包含必要的項目詳細信息:
$arr = array(
['id'] => 123
['title'] => 'some title'
['count'] => 1
['price'] => 9.99
);
然后,使用以下命令將該數組保存到$_SESSION
$_SESSION['cart'] = $arr;
當你准備其他項目添加到購物車中,創建一個具有相同鍵作為另一個數組$arr
- $newArr
-並追加數組到session變量:
$_SESSION['cart'][] = $newArr;
現在,當您准備讀取購物車中的所有物品時,就有一個關聯數組可以讀取:
for($x = 0; $x < count($_SESSION['cart']); $x++) {
echo $_SESSION['cart'][$x]['title'];
}
購物車的最佳方法之一是使用數據庫表。 1)只需創建一個表格購物車(id,guest-id,product-id,date)2)生成訪客ID並在點擊訪客后將其分配給會話添加到購物車
例:
if(isset($_GET['adtocart'])){
if(!isset($_SESSION['guest'])){
$ipaddress = $_SERVER['REMOTE_ADDR'];
$id = uniqid(rand());
$addnewguest = mysql_query("insert into guest values('$id', '$ipaddress', sysdate())");
if($addnewguest)
$_SESSION['guest'] = $id;
else
header('location: ../en/systemnotify.php?case=002');
}
$cartid = uniqid(rand());
$guestid = $_SESSION['guest'];
$productid = $_GET['adtocart'];
$getproduct = mysql_fetch_array(mysql_query("select * from product where id = '$productid'"));
$url = $getproduct['url'];
$title = mysql_real_escape_string($getproduct['title']);
$price = $getproduct['price'];
$image = $getproduct['image'];
$info = mysql_real_escape_string($getproduct['info']);
$cartid = uniqid(rand());
$addtocart = mysql_query("insert into cart values('$cartid', '$guestid', '$productid', '$url', '$title', '$price', '$image', '$info', sysdate()) ");
if($addtocart){
header('location: '.$_SERVER['HTTP_REFERER'].$gpath.'added');
}
else
print mysql_error();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.