johnbumble johnbumble - 6 months ago 23
PHP Question

Mixing up php and html files

Right now I have 2 files, a php file and an html file and I want to make a form. In my html file I have the contents of the website as well as my form. In my php file (named contact.php) I am trying to process the inputs in php. Right now when I click submit, the html form brings me to my php file and doesn't echo the inputs. I know I could make take all the html and php into one php file and this would work, but is there any way to do it with what I have now.

html code

<form action = "contact.php" method = "POST">
name: <input type = "text" name = "name"> <br>
email: <input type = "text" name = "email"> <br>
subject: <input type = "text" name = "subject"> <br>
<input type = "submit" value = "submit" name = "submit"> <br>
</form>


php code

<?php
$name = "";
$email = "";
$subject = "";
$nameError = "";
$emailError = "";
$subjectError = "";
$x = 5;
function filterData($data) {
$data = htmlspecialchars($data);
$data = stripslashes($data);
return $data;
}
$connection = mysqli_connect('x', 'x', 'x');
if (!connection) {
die('Could not connect: ' . mysqli_error());
}

mysqli_select_db(contact);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
//handles the name
if (empty($name)) {
$nameError = "please don't leave the name field blank";
}
else {
$name = filterData($_POST["name"]);
}
//handles the email
if (empty($email)) {
$emailError = "please don't leave the email field blank";
}
else {
$email = filterData($_POST["email"]);
}
//handles the subject
if (empty($subject)) {
$subjectError = "please don't leave this field blank";
}
else {
$subject = filterData($_POST["subject"]);
}

}

echo $name;
echo $subject;
echo $email;



?>

Answer

You're doing your empty check too early.

Change

if (empty($name)) {
    $nameError = "please don't leave the name field blank";
}
else {
    $name = filterData($_POST["name"]);
}

to

$name = filterData($_POST["name"]);
if (empty($name)) {
    $nameError = "please don't leave the name field blank";
}

Make similar changes to the other variable definitions.

You could also echo $nameError, $emailError and $subjectError to see a bit better what's going on.