我从事测验网站的项目,并且希望给用户编写问题的可能性。为此,我需要将问题插入数据库,但是我没有成功。我做错了什么?
我在php / mysqli中尝试了几种数据插入选项,但没有一个起作用。我的目标是创建一个表单,该表单可以自动将用户中的数据插入数据库中。经过几次尝试和重写后,数据库未更改。
这是表格的样子
<form action="includes/submit.inc.php" method="post">
<input type="text" name="Question" placeholder="Question">
<input type="text" name="AnsA" placeholder="A">
<input type="text" name="AnsB" placeholder="B">
<input type="text" name="AnsC" placeholder="C">
<input type="text" name="AnsD" placeholder="D">
<input type="text" name="CorrectAns" placeholder="The correct answer">
<select name="topic" placeholder="Topic">
<?php
require 'dbh.inc.php';
$sql="SELECT * FROM topics";
$req=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_assoc($req)){
$id=$row["IDTopic"];
$topic=$row["TopicName"];
echo "<option class='topic' value='".$id."'>".$topic."</option>";
}
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
这是我的commit.inc.php代码:
$question=$_POST['Question'];
$AnsA=$_POST['AnsA'];
$AnsB=$_POST['AnsB'];
$AnsC=$_POST['AnsC'];
$AnsD=$_POST['AnsD'];
$CorrectAns=$_POST['CorrectAns'];
$topic=$_POST['topic'];
if (empty($question) || empty($AnsA) || empty($AnsB) || empty($AnsC) || empty($AnsD) || empty($CorrectAns) || empty($topic) ){
header ("Location:../index.php?error=emptyfields");
exit();
}
else {
require 'dbh.inc.php';
$sql2="SELECT * from questions";
$req2=mysqli_query($conn, $sql2);
$questnum=mysqli_num_rows($req2)+1;
$stmt=$conn->prepare("INSERT INTO `questions` (`QuestNum`, `Question`, `AnsA`, `AnsB`, `AnsC`, `AnsD`, `CorrectAns`, `QuestTopic`) VALUES (?,?,?,?,?,?,?,?)");
$stmt->bind_param("issssssi",$questnum,$question,$AnsA,$AnsB,$AnsC,$AnsD,$CorrectAns,$topic);
$stmt->execute();
$stmt->close();
$conn->close();
header ("Location:../index.php?submit=succesful");
exit();
}