这是连接到mysql数据库的简单表单的代码
<html>
<head>
<title>CS90SI Project 2</title>
<script src="validation.js"></script>
</head>
<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 />
<?php if(isset($_POST['foodhealth'])) echo "checked='checked'"; ?>
Additional Notes:<br />
<textarea name="foodnotes" id="notesField"></textarea><br />
<input type="submit" value="Add" onclick="return validateForm();"></input>
</form>
<?php }else{ ?>
<!-- form handling and output printing stuff goes here -->
<?php
if(isset($_POST['foodhealth'])) {
$foodhealth = true;
} else {
$foodhealth = false;
}
$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($con, "mydb");
$result = mysqli_query($con, $insert);
echo "Food added successfully.";
while ($row = mysqli_fetch_array($result)) {
echo $row['Name'] . ", " . $row['Type'] . ", " . $row['NumCals'] . ", " . $row['Healthy'] . ", " . $row['Notes'];
echo "<br>";
}
mysqli_free_result($result);
mysqli_close($con);
} ?>
</body>
</html>
我提交数据并收到以下错误:
Notice: Undefined index: foodhealth in /Applications/XAMPP/xamppfiles/htdocs/vsingal5_hw2/index.php on line 38
Food added successfully.
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /Applications/XAMPP/xamppfiles/htdocs/vsingal5_hw2/index.php on line 47
Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given in /Applications/XAMPP/xamppfiles/htdocs/vsingal5_hw2/index.php on line 51
不知道为什么会发生这种情况,为复选框设置的布尔是否有问题,mysqli_fetch_array 有什么问题?