gpt4 book ai didi

PHP Form 不向 mySQL 数据库添加数据?

转载 作者:行者123 更新时间:2023-11-29 05:26:50 26 4
gpt4 key购买 nike

我在获取此表单以将数据成功提交到数据库时遇到问题。我已验证数据库/表存在(如下所示的模式)并且由于某种原因它没有将其插入数据库。当我尝试提交示例数据时,它不会更改页面,只是停在那里。到底是怎么回事?

<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)

最佳答案

提交按钮中的这个属性:

onclick="validateForm();return false;"

阻止表单提交。 return false 表示浏览器不应执行单击按钮的默认操作。

假设 validateForm() 函数返回一个指示验证是否成功的 bool 值,将其更改为:

onclick="return validateForm();"

改变:

} else { 
echo "Error adding person";
mysqli_error($con);

到:

} else { 
echo "Error adding person: " . mysqli_error($con);

以便显示错误信息。

并且您在 INSERT 语句末尾缺少 )

关于PHP Form 不向 mySQL 数据库添加数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com