问题描述
如何使用数据库和PHP会话来存储用户的购物车?我使用CodeIgniter,如果这有帮助。
How can I use a database and PHP sessions to store a user's shopping cart? I am using CodeIgniter, if that helps.
示例代码也很不错。
推荐答案
我会这样写一个添加到basket函数:
I would write an add to basket function like this:
function AddToBasket(){
if(is_numeric($_GET["ID"])){
$ProductID=(int)$_GET["ID"];
$_SESSION["Basket"][]=$ProductID;
$sOut.=ShowBasketDetail();
return $sOut;
}
}
在此购物篮功能中,会话数组。
In this shopping basket function we save Product IDs in an session array.
这是我将在show basket函数中:
Here is what I would have in the show basket function:
function ShowBasket(){
foreach($_SESSION[Basket] as $ProductID){
$sql="select * from products where ProductID=$ProductID";
$result=mysql_query($sql);
$row=mysql_fetch_row($result);
echo "Product: ".$row[0];
}
}
对于会话框中的每个ProudctID,查询输出产品信息。
For each ProudctID in our session basket we make a SQL query to output product information.
现在最后但并非最不重要的是,一个清晰的篮子函数:
Now last but not least, a clear basket function:
function ClearBasket(){
unset($_SESSION[Basket]);
}
不要忘记 session_start code>,然后将任何产品ID添加到会话列。也不要忘记
mysql_connect();
函数,你需要这个之前你对数据库进行任何查询。
Don't forget session_start();
before you add any Product IDs to your session basket. Also don't forget the mysql_connect();
function, you need this before you make any queries with the database.
这篇关于如何使用数据库和PHP会话来存储用户的购物车?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!