1

I'm not sure what I'm doing wrong. I'm trying to create a simple form which will not upload to the MySQL DB if the fields are empty. I also have some basic validation in the form. However, when I click 'save' the blank form is uploaded to the DB and I also do not get the error messages per field as I have highlighted them.

I would appreciate suggestion on where I err.

Here's my PHP Code:

<?php 

$firstNameError = $lastNameError = $idNumberError = $mobileNumberError = $emailError = $birthDateError = $languageTypeError = $interestError = "";
$firstName = $lastName = $idNumber = $mobileNumber = $email = $birthDate = $languageType = $interest = "";

if(isset($_POST['submit'])) {

    include 'dbconnect.php';

    try {

        $sql = "INSERT INTO members SET 
                firstName = :firstName,
                lastName = :lastName,
                idNumber = :idNumber,
                mobileNumber = :mobileNumber,
                email = :email,
                birthDate = :birthDate,
                languageType = :languageType,
                interest = :interest,
                created = :created";

        $stmt = $conn->prepare($sql);

        if (empty($_POST["firstName"])) {
            $firstNameError = "First Name is Required Please";
        } else { 
            $firstName = clean_data($_POST["firstName"]);
                if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
                    $firstNameError = "Only letters and white space allowed";
                }
        }
        if (empty($_POST["lastName"])) {
            $lastNameError = "Last Name is Required Please";                
        } else { 
            $lastName = clean_data($_POST["lastName"]);
                if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
                    $lastNameError = "Only letters and white space allowed";
                }
        }
        if (empty($_POST["idNumber"])) {
            $idNumberError = "ID Number is Required Please";                
        } else { 
            $idNumber = clean_data($_POST["idNumber"]);
            if (!preg_match("/^[0-9]{13}$/",$idNumber)) {
                    $idNumberError = "ID must be exactly 13 digits and no white spaces or other characters";
                }
        }
        if (empty($_POST["mobileNumber"])) {
            $mobileNumberError = "Mobile Nr is Required Please";                
        } else { 
            $mobileNumber = clean_data($_POST["mobileNumber"]);
            if (!preg_match("/^[0-9]{10}$/",$mobileNumber)) {
                    $mobileNumberError = "Your phone nr must be exactly 10 digits and no white spaces or other characters";
                }
        }
        if (empty($_POST["email"])) {
            $emailError = "Email is Required Please";               
        } else { 
            $email = clean_data($_POST["email"]);
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $emailError = "Please enter a valid email address";
            }
        }
        if (empty($_POST["birthDate"])) {
            $birthDateError = "Birth Date is Required Please";              
        } else { 
            $birthDate = clean_data($_POST["birthDate"]);
            list($dd,$mm,$yyyy) = explode('-',$birthDate);
            if (!checkdate($yyyy,$mm,$dd)) {
                $birthDateError = "Please use the format YYYY-MM-DD";
            }
        }
        if (empty($_POST["languageType"])) {
            $languageTypeError = "Languge Type is Required Please";             
        } else { 
            $languageType = clean_data($_POST["languageType"]);
        }
        if (empty($_POST["interest"])) {
            $interestError = "Interest is Required Please";             
        } else { 
            $interest = clean_data($_POST["interest"]);
        }

        $stmt->bindParam(':firstName', $firstName);
        $stmt->bindParam(':lastName', $lastName);
        $stmt->bindParam(':idNumber', $idNumber);
        $stmt->bindParam(':mobileNumber', $mobileNumber);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':birthDate', $birthDate);
        $stmt->bindParam(':languageType', $languageType);
        $stmt->bindParam(':interest', $interest);

        $created = date('Y-m-d H:i:s');
        $stmt->bindParam(':created', $created);

        if($stmt->execute()){
            echo "<div class='alert alert-success'>Member was saved.</div>";
        } else {
            echo "<div class='alert alert-danger'>Unable to save this member.</div>";
        }
    }

    catch(PDOException $exception){
        die('ERROR: ' . $exception->getMessage());
    }

}

function clean_data($data) {

    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;

}

?>

And here is my HTML Code:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <table class='table table-hover table-responsive table-bordered'>
        <tr>
            <td>First Name: *</td>
            <td><input type='text' name='firstName' class='form-control' /></td>
        </tr>
        <tr>
            <td>Last Name: *</td>
            <td><input type='text' name='lastName' class='form-control' /></td>
        </tr>
        <tr>
            <td>ID Number: *</td>
            <td><input type='text' name='idNumber' class='form-control' /></td>
        </tr>
        <tr>
            <td>Mobile Number: *</td>
            <td><input type='text' name='mobileNumber' class='form-control' /></td>
        </tr>
        <tr>
            <td>Email: *</td>
            <td><input type='text' name='email' class='form-control' /></td>
        </tr>
        <tr>
            <td>Birth Date</td>
            <td><input type='text' name='birthDate' class='form-control' /></td>
        </tr>
        <tr>
            <td>Language</td>
            <td>

                <select class="form-control" name="languageType">

                  <option>Select One...</option>
                  <option>Afrikaans</option>
                  <option>English</option>
                  <option>Zulu</option>
                  <option>Xhosa</option>
                  <option>Venda</option>
                  <option>French</option>

              </select>
            </td>
        </tr>
        <tr>
            <td>Interest</td>
            <td>

                <select class="form-control" name="interest">

                  <option>Select One...</option>
                  <option>Golf</option>
                  <option>Rugby</option>
                  <option>Tennis</option>
                  <option>Cricket</option>
                  <option>Swimming</option>
                  <option>Hiking</option>
                  <option>Surfing</option>
                  <option>Movies</option>
                  <option>Swords</option>

                </select>

            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type='submit' name='submit' value='Save' class='btn btn-primary' />
                <a href='index.php' class='btn btn-danger'>Back to view members</a>
            </td>
        </tr>
    </table>
</form>
4
  • Thanks Difster, not sure why the thread posted like that Commented Jul 31, 2017 at 6:54
  • You know, if you want to include jQuery on the front end, they have an excellent validation class built in. Commented Jul 31, 2017 at 6:56
  • You do your validation as in, if empty foo, fooError = 'foo can't be empty', but then do the insert anyway. Mark a boolean such as $is_valid as false at that point, and then check that before the insert. Commented Jul 31, 2017 at 7:01
  • Yes Difster, I need to look more into JQuery. Thanks for the advice Commented Jul 31, 2017 at 10:05

6 Answers 6

2

Unless I'm mistaken (and I frequently am), it doesn't look like you're testing to see if there are error messages before trying to write to the database. You should do all of your data validation first and THEN put the sql statment in the try/catch but only if all the errors evaluate to false. If you think you can rearrange that on your own, go for it. If you need help, let me know.

Another hint, set another variable called $error = false; at the beginning and then if any of the error messages get triggered, set it to to true. Then, for your database write, you only have to check to see if($error == true) ...

Sign up to request clarification or add additional context in comments.

1 Comment

I must admit that I made a schoolboy error in not echo'ing my error messages. I fixed that now
1

You are assigning error string for every unsuccessful field name.

But, not using it anywhere.

Modify the code to:

if ($firstNameError != '' OR  $lastNameError != '' OR  $idNumberError != '' OR  $mobileNumberError != '' OR  $emailError != '' OR  $birthDateError != '' OR  $languageTypeError != '' OR  $interestError != '') {
 echo "<div class='alert alert-danger'>Unable to save this member.</div>";
 // Die or redirect to error page.
}
else {
 // Code for inserting into database.
}

2 Comments

@Progrock, thanks for comment. I am looking into the link you have sent and will update my answer accordingly once I read it out. Thanks for sharing such a knowledgeable thing. This is the way SO users get benefited.
@Progrock, updated the answer and removed the action related thing. Thanks :)
0

It will be much simpler to do this validation prior to POST:

<td><input type='text' name='firstName' class='form-control' required placeholder="Enter a valid First Name :)"/></td>

Place "required" property to each mandatory input field. This validation is done prior to POST so you won't need another validation from backend side.

2 Comments

It's good to have both server side and client side validation/checks.
I agree with Progrock that validation should be done on both ends. I however, did not do any validation on the front-end. So thanks Alexandru - the required attribute is a quick front-end fix
0

     <form action="" method="post">
     <table class='table table-hover table-responsive table-bordered'>
                        <tr>
                            <td>First Name: *</td>
                            <td><input type='text' name='firstName' class='form-control' required/></td>
                        </tr>
                        <tr>
                            <td>Last Name: *</td>
                            <td><input type='text' name='lastName' class='form-control' required /></td>
                        </tr>
                        <tr>
                            <td>ID Number: *</td>
                            <td><input type='text' name='idNumber' class='form-control' required/></td>
                        </tr>
                        <tr>
                            <td>Mobile Number: *</td>
                            <td><input type='text' name='mobileNumber' class='form-control' required/></td>
                        </tr>
                        <tr>
                            <td>Email: *</td>
                            <td><input type='text' name='email' class='form-control' required /></td>
                        </tr>
                        <tr>
                            <td>Birth Date</td>
                            <td><input type='text' name='birthDate' class='form-control' required/></td>
                        </tr>
                        <tr>
                            <td>Language</td>
                            <td>
    
                                <select class="form-control required" name="languageType" required>
    
                                  <option>Select One...</option>
                                  <option>Afrikaans</option>
                                  <option>English</option>
                                  <option>Zulu</option>
                                  <option>Xhosa</option>
                                  <option>Venda</option>
                                  <option>French</option>
    
                              </select>
                            </td>
                        </tr>
                        <tr>
                            <td>Interest</td>
                            <td>
    
                                <select class="form-control" name="interest" required>
    
                                  <option>Select One...</option>
                                  <option>Golf</option>
                                  <option>Rugby</option>
                                  <option>Tennis</option>
                                  <option>Cricket</option>
                                  <option>Swimming</option>
                                  <option>Hiking</option>
                                  <option>Surfing</option>
                                  <option>Movies</option>
                                  <option>Swords</option>
    
                                </select>
    
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <input type='submit' name='submit' value='Save' class='btn btn-primary' />
                                <a href='index.php' class='btn btn-danger'>Back to view members</a>
                            </td>
                        </tr>
                    </table>
                    </form>

3 Comments

Please add an explanation to your answer.
The required keyword is use to fire non empty field error meassge
Please add the explanation to your answer (edit it), otherwise it's just a wall of code.
0

So I added 'throw new exception' in the php code which blocks the data from being submitted to the db. Below I highlighted the change.

if (empty($_POST["firstName"])) {
                        *throw new Exception ("First Name is a Required Field");*
                    } else { 
                        $firstName = clean_data($_POST["firstName"]);
                            if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
                                *throw new Exception ("Only letters and whitespace allowed in First Name");*
                            }
                    }
                    if (empty($_POST["lastName"])) {
                        *throw new Exception ("Last Name is a Required Field");*                
                    } else { 
                        $lastName = clean_data($_POST["lastName"]);
                            if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
                                *throw new Exception ("Only letters and whitespace allowed in Last Name");*
                            }
                        }
                    if (empty($_POST["idNumber"])) {
                        *throw new Exception ("ID Number is a Required Field");*            
                    } else { 
                        $idNumber = clean_data($_POST["idNumber"]);
                        if (!preg_match("/^[0-9]{13}$/",$idNumber)) {
                                *throw new Exception ("ID Number may only contain numbers and may only be 13 digits long");*
                            }
                    }
                    if (empty($_POST["mobileNumber"])) {
                        *throw new Exception ("Mobile Number is a Required Field");*                
                    } else { 
                        $mobileNumber = clean_data($_POST["mobileNumber"]);
                        if (!preg_match("/^[0-9]{10}$/",$mobileNumber)) {
                                *throw new Exception ("Mobile Number may only contain numbers and may only be 10 digits long");*
                            }
                    }
                    if (empty($_POST["email"])) {
                        *throw new Exception ("Email is a Required Field");*                
                    } else { 
                        $email = clean_data($_POST["email"]);
                        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            *throw new Exception ("Please make sure you entered a valid email");*
                        }
                    }
                    if (empty($_POST["birthDate"])) {
                        *throw new Exception ("D.O.B. is a Required Field");*           
                    } else { 
                        $birthDate = clean_data($_POST["birthDate"]);
                    }
                    if (empty($_POST["languageType"])) {
                        *throw new Exception ("Please select a language");*                 
                    } else { 
                        $languageType = clean_data($_POST["languageType"]);
                    }
                    if (empty($_POST["interest"])) {
                        *throw new Exception ("Please select a interest");*             
                    } else { 
                        $interest = clean_data($_POST["interest"]);
                    }

                    $stmt->bindParam(':firstName', $firstName);
                    $stmt->bindParam(':lastName', $lastName);
                    $stmt->bindParam(':idNumber', $idNumber);
                    $stmt->bindParam(':mobileNumber', $mobileNumber);
                    $stmt->bindParam(':email', $email);
                    $stmt->bindParam(':birthDate', $birthDate);
                    $stmt->bindParam(':languageType', $languageType);
                    $stmt->bindParam(':interest', $interest);

                    $created = date('Y-m-d H:i:s');
                    $stmt->bindParam(':created', $created);

                    if($stmt->execute()){
                        echo "<div class='alert alert-success'>Member was saved.</div>";
                    } else {
                        echo "<div class='alert alert-danger'>Unable to save this member.</div>";
                    }
                }

                catch(Exception $exception){
                    *echo '<h4 style="color:red;">' . $exception->getMessage() . '</h4>';*
                }

In html I just added the required attribute as shown below:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
            <table class='table table-hover table-responsive table-bordered'>
                <tr>
                    <td>First Name: *</td>
                    <td><input type='text' name='firstName' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Last Name: *</td>
                    <td><input type='text' name='lastName' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>ID Number: *</td>
                    <td><input type='text' name='idNumber' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Mobile Number: *</td>
                    <td><input type='text' name='mobileNumber' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Email: *</td>
                    <td><input type='text' name='email' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Birth Date: *</td>
                    <td><input type='date' name='birthDate' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Language: *</td>
                    <td>

                        <select class="form-control" name="languageType" required>

                          <option>Select One...</option>
                          <option>Afrikaans</option>
                          <option>English</option>
                          <option>Zulu</option>
                          <option>Xhosa</option>
                          <option>Venda</option>
                          <option>French</option>

                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Interest: *</td>
                    <td>

                        <select class="form-control" name="interest" required>

                          <option>Select One...</option>
                          <option>Golf</option>
                          <option>Rugby</option>
                          <option>Tennis</option>
                          <option>Cricket</option>
                          <option>Swimming</option>
                          <option>Hiking</option>
                          <option>Surfing</option>
                          <option>Movies</option>
                          <option>Swords</option>

                        </select>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type='submit' name='submit' value='Save' class='btn btn-primary' />
                        <a href='index.php' class='btn btn-danger'>Back to view members</a>
                    </td>
                </tr>
            </table>
        </form>

7 Comments

What if your database insert throws an exception?
I'm not sure how a user is expected to correct any errors? Using exceptions, only one input error presents a warning at a time. With the user potentially having to go back a page and try again until all fields are correct. Could you present all input errors at once to the user?.
I'd constrain the users choices for language and interest with validation also. Perhaps a non-issue but the user could submit values not in those select lists.
Your clean data function uses htmlspecialchars, why?
Hi Prgrock, as far as I know htmlspecialchars help to prevent users entering malicious code. Just putting it in there in case someone tries to hack me. Won't do harm would it?
|
-1

You're missing returns. In your codes, you have

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailError = "Please enter a valid email address";
}

This will only assign your message to variable but will still proceed in saving. try something like this

$sErrors = '';    
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $sErrors  .= "Please enter a valid email address \n";
    }
if (empty($_POST["mobileNumber"])) {
            $sErrors  .= "Mobile Nr is Required Please\n";                
        }

if (strlen($sErrors) > 0) {
    return $sErrors;
}

of course you'll have to do it in all your if validator

3 Comments

Where would this return to exactly?
Have you tried it first? I'm assuming your page will go to the value of $_SERVER["PHP_SELF"] and will display the message in your page.
@perseusi the point being that currently the validations are in if control structures, not in a function. And a return will just short circuit the script, and error messages will be lost. The web client could do with appropriate feedback and hand holding. This is half an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.