Hi
I'm have a PHP form that submits to a MYSQL database and I'm trying to make it so when any form input field is empty the user gets a message below that field and the data isn't submitted. I can't seem to get it work though?
The data submits OK when I don't have any validation but obviously if the fields are empty then a blank record just gets added to the database.
<?php
// submit data to database
if (isset($_POST['submit'])) {
// assign variable names to name attributes from the form
$firstname = $_POST['first-name'];
$email = $_POST['email'];
// This is the attempted validation code
if(empty($firstname)) {
$error= "<br>- Please enter your firstname";
}
if(empty($email)) {
$error="<br>- Please enter your email";
}
if ($error) {
$result="<p class='alert error'>There is an error. Please correct the following: {$error}</p>";
} else {
// This is when the data is submitted
$query = "INSERT INTO users(firstname, email) VALUES(?,?)";
$stmt = $connection->prepare($query);
$stmt->bind_param("ss", $f, $e);
$f = $firstname;
$e = $email;
$stmt->execute();
$stmt->close();
$connection->close();
header("Location: index.php"); // makes page refresh after query so new records show in HTML table
}
}
?>