我无法将此表单成功提交到数据库。我已经验证了数据库/表存在(下面显示的模式),并且由于某种原因它没有将它插入到数据库中。当我尝试提交样本数据时,它不会更改页面而只是坐在那里。到底是怎么回事?
<body>
<?php if($_SERVER["REQUEST_METHOD"] != "POST"){ ?>
<h1>My Favorite Foods</h1>
<form action="index.php" method="post" id="foodForm">
Name: <input type="text" name="foodname" id="nameField"></input><br />
Type: <select name="foodtype" id="typeField">
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
<option value="dairy">Dairy</option>
<option value="meat">Meat</option>
<option value="grain">Grain</option>
<option value="other">Other</option>
</select><br />
Number of Calories: <input type="text" name="foodcals" id="calsField"></input><br />
Healthy? <input type="checkbox" name="foodhealth" value="healthy" id="healthyField"></input><br />
Additional Notes:<br />
<textarea name="foodnotes" id="notesField"></textarea><br />
<input type="submit" value="Add" onclick="validateForm();return false;"></input>
</form>
<?php }else{ ?>
<!-- form handling and output printing stuff goes here -->
<?php $insert = "INSERT INTO Foods(Name, Type, NumCals, Healthy, Notes) VALUES ('$_POST[foodname]', '$_POST[foodtype]', '$_POST[foodcals]', '$_POST[foodhealth]', '$_POST[foodnotes]'";
$con = mysqli_connect("localhost","root");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db("mydb");
$result = mysqli_query($con, $insert);
if ($result) {
echo "Food added successfully.";
/*while ($row = mysqli_fetch_array($result)) {
echo $row['Name'] . ", " . $row['Type'] . ", " . $row['NumCals'] . ", " . $row['Healthy'] . ", " . $row['Notes'];
echo "<br>";
} */
} else {
echo "Error adding person";
mysqli_error($con);
}
} ?>
</body>
</html>
架构:
食物(PID INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(PID),Name VARCHAR(20),Type VARCHAR(9),NumCals INT,Healthy BOOL,Notes TEXT)
答案 0 :(得分:3)
提交按钮中的此属性:
onclick="validateForm();return false;"
阻止表单提交。 return false
表示浏览器不应通过单击按钮执行默认操作。
假设validateForm()
函数返回一个布尔值,指示验证是否成功,请将其更改为:
onclick="return validateForm();"
变化:
} else {
echo "Error adding person";
mysqli_error($con);
为:
} else {
echo "Error adding person: " . mysqli_error($con);
这样就会显示错误信息。
您在)
声明的末尾错过了INSERT
。