I have created a script using procedural php it uses 2 functions
function 1# is signup sending information to the database.
function 2# is a validate required fields.
I call these in the form and it works but only in reverse effect and I cannot figure out why, if the fields are empty it allows you to submit and send a blank query and if the fields have values it returns fields are required.
my validate function
function validate($name, $email, $password): array
{
$errors = [];
if ($name) {
$errors[] = "Name is required";
}
if ($email) {
$errors[] = "Email is required";
}
if ($password) {
$errors[] = "Please enter a valid password";
}
return $errors;
}
The Form Page
if ($_SERVER['REQUEST_METHOD'] === "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$errors = validate($name, $email, $password);
if (empty($errors)) {
signup($email, $name, $password);
}
}
and then the code to display the error
My Form
<?php if (!empty($errors)) : ?>
<ul>
<?php foreach ($errors as $error) : ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form name="form-registration" method="post">
<fieldset>
<div>
<label for="name">Name</label>
<input id="name" name="name" value="">
</div>
</fieldset>
<fieldset>
<div>
<label for="email">Email Address</label>
<input id="email" name="email" value="">
</div>
</fieldset>
<fieldset>
<div>
<label for="password">Password</label>
<input type="password"name="password">
</div>
</fieldset>
<input type="submit" value="insert">
</form>