我正在添加到购物车。一切都很顺利。但是当我试图将会话2d数组中的数据存储到数据库中时,它没有正确发生,即最后一个产品的id和qty仅被存储。
这是用于在数据库中存储数据的页面
<?php
session_start();
echo "<pre>";
$value=$_SESSION['cart'];
foreach ($_SESSION['cart'] as $item) {
// echo 'p_id: ', $item['id'], '<br />';
// echo 'p_size: ', $item['p_size'], '<br />';
//echo 'p_qty: ', $item['qty'], '<br /><br />';
}
//print_r($value);
echo"done";
echo $address=$_GET['add'];
echo "<br>";
echo $con=$_GET['cont'];
echo "<br>";
echo $mail=$_GET['mail'];
echo "<br>";
echo $pay=$_GET['mode'];
echo "<br>";
echo $total=$_GET['total'];
echo "<br>";
//echo "".$_SESSION['cart'];
//echo $total=$_SESSION['id'];
//echo $total=$_GET['total'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "admin1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "connected successfully";
echo"<br>";
foreach ($_SESSION['cart'] as $value){
// print_r($_SESSION);
//print_r($_SESSION['cart']);
$sql="INSERT INTO orders(total,id,qty,address,cont,mail,mode) values ('".$total."','".$value['id']."','".$value['qty']."','".$address."','".$con."','".$mail."','".$pay."')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
答案 0 :(得分:1)
你应该在foreach循环中添加$ conn-&gt;查询($ sql)。 试试吧:
<?php
session_start();
echo "<pre>";
$value=$_SESSION['cart'];
foreach ($_SESSION['cart'] as $item) {
// echo 'p_id: ', $item['id'], '<br />';
// echo 'p_size: ', $item['p_size'], '<br />';
//echo 'p_qty: ', $item['qty'], '<br /><br />';
}
//print_r($value);
echo"done";
echo $address=$_GET['add'];
echo "<br>";
echo $con=$_GET['cont'];
echo "<br>";
echo $mail=$_GET['mail'];
echo "<br>";
echo $pay=$_GET['mode'];
echo "<br>";
echo $total=$_GET['total'];
echo "<br>";
//echo "".$_SESSION['cart'];
//echo $total=$_SESSION['id'];
//echo $total=$_GET['total'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "admin1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "connected successfully";
echo"<br>";
$success= false;
foreach ($_SESSION['cart'] as $value){
// print_r($_SESSION);
//print_r($_SESSION['cart']);
$sql="INSERT INTO orders(total,id,qty,address,cont,mail,mode) values ('".$total."','".$value['id']."','".$value['qty']."','".$address."','".$con."','".$mail."','".$pay."')";
if ($conn->query($sql) === TRUE) {
$success = true;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
$success = false;
break;
}
}
if($success)
echo "New record created successfully";
?>