这是连接到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有什么问题?

最佳答案

您在这里缺少一堆引号:

 VALUES('$_POST[foodname]','$_POST[foodtype]','$_POST[foodcals]','$_POST[foodhealth]','$_POST[foodnotes]')";


他们应该是:

 VALUES('{$_POST['foodname']}','{$_POST['foodtype']}','{$_POST['foodcals']}','{$_POST['foodhealth']}','{$_POST['foodnotes']}')";


变量包含在{}

关于php - PHP未定义索引和mysqli_fetch_array()不接受参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19204575/

10-12 02:38