I am trying to make my form validation and db insert script work but am facing problems again. I am using an elseif statement to do:
Check if the form was actually submitted by the user clicking the submit button and all data fields completed, if not warn and redirect back to the form page (this is the only part that seems to be working)
If the form has been completed fully and submit button clicked then connect to mysql server and select db or die and display error message
If there is a connection to the database then insert the form data to the table
I can prevent the entry of empty fields but that is all,everything else seems to break. I cannot seem to figure out why. tail -f /var/log/apache2/error.log
displays nothing. Perhaps I have over complicated things. I have been using this site as a reference and http://www.w3schools.com/php/php_if_else.asp for elseif syntax, newbie still screwing things up.
Here is the code:
<?php
//Form fields passed to variables
$manu = mysql_real_escape_string($_POST['inputManu']);
$model = mysql_real_escape_string($_POST['inputModel']);
$desc = mysql_real_escape_string($_POST['inputDesc']);
//Connect to database using $conn
include ('connection.php');
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
//Check for empty fields
if ($_POST['submit'])
{
foreach($_POST as $val)
{
if(trim($val) == '' || empty($val))
{
die();
echo "Please complete all form fields!";
echo "<meta http-equiv='Refresh' content='3; URL=../add.php'>";
//header("Location: ../add.php?error=empty_fields");
}
}
}
elseif (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
else
{
//echo "1 record added";
echo "Success, You added the ".$manu." ".$model."";
echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
mysqli_close($conn);
?>