我是一名初级开发人员,试图使用PHP和MySQL创建一个简单的购物车。尝试通过使用“添加到购物车”按钮在数据库中插入数据时遇到问题。我不得不提到,我试图将购物车数据存储在数据库中,而不是在会话中存储。
这是我来自“ browse.php”文件的代码,用户可以在其中查看所有可用的产品(书籍)并将其添加到购物车中:
$sql = "SELECT * FROM books ORDER BY bookTitle ASC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$isbn = $row['bookISBN'];
$title = $row ['bookTitle'];
$author = $row['bookAuthor'];
$price = $row['bookPrice'];
$cover = $row['bookCover'];
echo "<div style='border:1px solid black; width:420px; height:230px'>";
echo "<br>";
echo "<img src='bookcovers/$cover' alt='Book Cover' style='float:left;width:133px;height:190px;margin-left:10px;margin-right:35px;'>";
echo "<p style='text-align:left'>";
echo "<b>Title:</b> $title <br>";
echo "<b>Author:</b> $author <br>";
echo "<b>ISBN:</b> $isbn <br><br>";
echo "<b>Price:</b> € $price <br><br>";
//This part is only visible if a user is logged in (session is set)
if (isset($_SESSION["my_username"])){
$username = $_SESSION["my_username"];
echo "Quantity: <input type='number' name='quantity' min='1' max='99' width='4px' value='1'>";
echo "<br><br>";
echo "<a href='cart.php?action=add_item&isbn=".$isbn."'>Add to Cart</a>";
}
echo "</p>";
echo "<br><br>";
echo "</div>";
echo "<br><br><br>";
}
} else {
echo "0 results";
}
这是我在“ cart.php”文件中的代码:
switch(isset($_GET['action'])) {
case "add_item":
AddProduct($_GET["isbn"]);
ShowCart();
break;
case "remove_item":
RemoveProduct($_GET["isbn"]);
ShowCart();
break;
}
//Adds one item to the cart
function AddProduct($bookISBN) {
$my_username = $_SESSION['my_username'];
//db connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ebooksdb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM cart WHERE username = '".$my_username."' and bookISBN = $bookISBN";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_row($result);
$numRows = $row[0];
if($numRows == 0) {
$sql2 = "INSERT INTO cart(username, bookISBN, quantity) VALUES ($my_username, $bookISBN, 1)";
$result2 = mysqli_query($conn, $sql);
}
else {
UpdateProduct($bookISBN);
}
}
function UpdateProduct($bookISBN) {
$sql = "UPDATE cart SET quantity = quantity + 1 WHERE username = '".$my_username."' and bookISBN = $bookISBN";
$result = mysqli_query($conn, $sql);
}
用户名和bookISBN是主键。
通过检查,我注意到它是通过AddProduct函数获得的,但是它没有将数据插入数据库中,也没有更新它们。