即时开发购物车项目,一切正常。我想问一下如何将所有购物车产品逐一插入数据库
下面是我尝试的代码,但它只插入第一个会话行而不是插入所有。
这是代码:
$User_Email=$_SESSION['User_Email'];
$date=date("d-m-Y");
foreach($_SESSION["shopping_cart"] as $v){
$sql = "INSERT INTO reservation (check_in,check_out,room_id,hotel_id,User_Email,date)
values
('{$v['Checkin']}','{$v['Checkout']}','{$v['room_id']}','{$v['room_id']}','$User_Email','$date')";
$update = mysqli_query($connection, $sql);
if ($update) {
$_SESSION['success'] = 'Information updated successfully';
header("location: my_account.php");
exit;
} else {
$_SESSION['errormsg'] = 'Someting is wrong in updating your Information, Please try again later.';
header("location: my_account.php");
exit;
}}
请告诉我如何将所有购物车价值插入数据库。
提前致谢。
您在循环中使用header()
,这将在第一次迭代中重定向或失败成功。
您可以在变量中存储成功或失败状态
if ($update) {
$status = 1;
} else {
$status = 0;
}
然后,将您的条件移到循环之外,如:
if($status) // your success
{
header('your location');
exit;
}
else{ // failure
header('your location');
exit;
}
确保$status
在顶级声明中宣布为$status = 0;
。
请注意,为了防止SQL注入使用PDO
,您的代码对SQL注入是开放的
有用的链接:
How can I prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?