php产品数量限制,php - 从数据库而不是会话中获取特定产品的数量-购物车(PHP&MySQL) - 堆栈内存溢出...

本文探讨了作者在将PHP会话购物车迁移到MySQL持久化时,遇到的问题,即如何从cart表中正确提取特定productId的quantity。作者分享了现有的代码片段,并寻求如何避免使用$productId在SQL查询中,以提高效率并防止SQL注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我一直在尝试从基于会话的php购物车开始创建一个基于MySQL的持久购物车应用程序。 cart表的结构为userid | productid | quantity | postingdate userid | productid | quantity | postingdate userid | productid | quantity | postingdate 。 在基于会话的实现中,特定产品的数量信息存储在$_SESSION['cart'][$row['id']]['quantity']; ; 我在从数据库的cart表中检索某种产品的数量信息时遇到了麻烦,因为我似乎无法找到如何提取$getquantity查询所需的productId 。

$sql1 = "SELECT * FROM cart WHERE userid='$userId'"; //selects the user's cart

$query1=mysqli_query($con,$sql1);

if (!empty($query1)) { //if the user's cart isn't empty

while($row = mysqli_fetch_array($query1)){

$query = mysqli_query($con,"SELECT * FROM products JOIN cart ON cart.productid=products.id

ORDER BY cart.postingDate DESC"); //selects all the products in the current user's cart

}

$totalprice=0;

$totalqunty=0;

if (!empty($query)) {

while ($row = mysqli_fetch_array($query)) { //for each product

//$quantity=$_SESSION['cart'][$row['id']]['quantity']; //SESSION IMPLEMENTATION

$id = $row['id'];

$quantity = mysqli_query($con,"SELECT quantity FROM cart WHERE userid='$userId' AND productid='$id'"); //MY IMPLEMENTATION, THE WRONG PART IS WITH $id

$subtotal= $quantity*$row['productPrice']+$row['shippingCharge'];

$totalprice += $subtotal;

$_SESSION['qnty']=$totalqunty+=$quantity; //SESSION IMPLEMENTATION

}

}

}

我试过$row['id']但是它从$query返回的记录中返回所有productid的数组,而MySQl似乎不接受它,而我需要$getquantity在每个productid上运行。 请不要介意它很容易受到SQL注入的影响,因为我将在以后的阶段中对此进行介绍。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值