Reputation: 304
I am having trouble getting this form to successfully submit the data to the database. I have verified that the database/table exists (schema shown below) and for some reason it's not inserting it into the database. When I try to submit sample data, it doesn't change the page and just sits there. What is going on?
<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>
Schema:
Foods(PID INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(PID),Name VARCHAR(20),Type VARCHAR(9),NumCals INT,Healthy BOOL,Notes TEXT)
Upvotes: 1
Views: 409
Reputation: 780723
This attribute in the submit button:
onclick="validateForm();return false;"
prevents the form from submitting. return false
means that the browser should not perform the default action from clicking the button.
Assuming the validateForm()
function returns a boolean indicating whether validation was successful, change that to:
onclick="return validateForm();"
Change:
} else {
echo "Error adding person";
mysqli_error($con);
to:
} else {
echo "Error adding person: " . mysqli_error($con);
So that the error message will be displayed.
And you're missing the )
at the end of your INSERT
statement.
Upvotes: 3