Generah Ben Generah Ben - 2 months ago 5
PHP Question

How do I stop this code from running if a single condition is not met PHP

This code still runs to the end and submit even if condition is not met. I want to stop it from running and echo an error if any condition is missed. Kindly help please. Note: I have tried exit() and it affected the whole html under from running.

$verifiedPhone = phoneNumberValidator($phone);
$correctsurname = nameValidator($surname);
$correctlastname = nameValidator($lastname);
$correctusername = nameValidator($username);
if(!$verifiedPhone){
echo "<p class='alert alert-warning'>Please use a Valid Phone Number</p>";

}
if(!$correctsurname){
echo "<p class='alert alert-warning'>Surname can only contain alphabets</p>";
}
if(!$correctlastname) {
echo "<p class='alert alert-warning'>Last Name can only contain alphabets</p>";
}
if (!$correctusername) {
echo "<p class='alert alert-warning'>Username can only contain alphabets</p>";
}
$checkuser = " SELECT * FROM staff
WHERE username = '$correctusername'";
$checkuserresult = mysqli_query($connection, $checkuser);
$checkuserrow = mysqli_num_rows($checkuserresult);
if($checkuserrow > 0){
echo "<p class='alert alert-danger'>Username \"".$username."\" already exist! Try another</p>";
}
else{
$harsedpassword = md5("$password");
$datainsert = " INSERT INTO staff (surname, lastname, phone, username, password) VALUES ('$correctsurname', '$correctlastname', '$verifiedPhone', '$username','$harsedpassword')";
$datainsertresult = mysqli_query($connection, $datainsert);
if($datainsertresult){
echo "<p class='alert alert-success'><b>Staff Added Successfully</b></p>";
}

Answer

Either use else ifs

if(!$correctsurname){
                        echo "<p class='alert alert-warning'>Surname can only contain alphabets</p>";
}
else if(!$correctlastname) {
                        echo "<p class='alert alert-warning'>Last Name can only contain alphabets</p>";
}
else if (!$correctusername) {
                        echo "<p class='alert alert-warning'>Username can only contain alphabets</p>";
}
else {
    //the rest

or die("message") if you must:

if(!$correctsurname){
                        die("<p class='alert alert-warning'>Surname can only contain alphabets</p>");     

}