找到了答案!
对于任何想知道出什么问题的人: 没有将数据插入数据库,因为我没有在addbook.php中启动会话,并且因为数据库中的登录列不能为空-即使没有运行代码,也没有创建记录,因为没有变量$ _SESSION ['login']。感谢Progman对“如何获取MySQLi错误”的评论,我得以抓住它。谢谢大家的帮助!
已更新:问题出在mysqli_stmt_execute
上,但是我现在不知道如何处理
我在将数据插入MySQL数据库时遇到问题。问题在于,没有“可见”错误,代码应该可以正常工作,但是没有数据插入数据库。
寻找正确的表名-已选中!
寻找正确的变量/列名-已选中!
我也不认为连接有问题,因为代码通过连接语句运行。
我的表格(用于有关旧书/学习材料的网站):
<form method="post" action="includes/addbook.php">
<p class="bookAdd">Name of the book:<input class="book" type="text" name="bookName" placeholder="Name of the book"></p>
<p class="bookAdd">Author of the book:<input class="book" type="text" name="bookAuthor" placeholder="Author of the book"></p>
<p class="bookAdd">Book's type:
<select name="types">
<?php
require 'includes/db.php';
$query = "SELECT * FROM types";
$result = mysqli_query($conn, $query) or die ("SQL Error");
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='".$row['bookType']."'>".$row['bookType']. "</option>";
}
?>
</select></p>
<p class="bookAdd">Book's subject:
<select name="subjects">
<?php
require 'includes/db.php';
$query = "SELECT * FROM subjects ORDER BY bookSubject";
$result = mysqli_query($conn, $query) or die ("SQL Error");
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='".$row['bookSubject']."'>".$row['bookSubject']. "</option>";
}
?>
</select></p>
<p class="bookAdd">Book's price:<input class="book" type="text" name="bookPrice" placeholder="What's the price?"></p>
<p class="bookAdd">Description:<input class="book-desc" type="text" name="bookDesc" placeholder="Description of your add"></p>
<input class="submit-big" type="submit" name="submit-book-add" value="Add book!">
</form>
还有我的addbook.php文件:
<?php
if (isset($_POST['submit-book-add'])) {
require 'db.php';
$login = $_SESSION['login'];
$bookName = $_POST['bookName'];
$bookAuthor = $_POST['bookAuthor'];
$bookType = $_POST['types'];
$bookSubject = $_POST['subjects'];
$bookPrice = $_POST['bookPrice'];
$bookDesc = $_POST['bookDesc'];
if (empty($bookName) || empty($bookAuthor) || empty($bookType) || empty($bookSubject) || empty($bookPrice) || empty($bookDesc)) {
header("location: ../account.php?error=emptyfields");
exit();
}
else {
$sql = "INSERT INTO books (login, bookName, bookAuthor, bookType, bookSubject, bookPrice, bookDesc) VALUES(?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("location: ../account.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "sssssss", $login, $bookName, $bookAuthor, $bookType, $bookSubject, $bookPrice, $bookDesc);
mysqli_stmt_execute($stmt);
header("location: ../account.php?add=success");
exit();
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("location: ../account.php");
exit();
}
也在这里-我应该始终使用占位符将数据插入数据库中还是仅使用用于注册网站的信息?
也许我错过了一些东西,我一直在寻找常见的PHP错误处理,这时我只是迷失了思路,这基本上是我真正完成uni项目之前要做的最后一件事。
感谢您的回答!
更新:感谢评论者,我确实检查了mysqli_stmt_execute中是否发生了错误,所以现在我要面对它!