0

I am still new in PHP and right now I'm trying to send data to an SQL database. Let's say for form its called cust_form.php. All the data submitted from there I send it to cust_details.php. My problems right now are -

1) How to validate the data before it been sent to database.

2) How to display the error in cust_form.php and the incorrect data will not been sent / saved to database.

Example of inserting input

Error occured in email field although correct email been given

I already google for this kind of problem but all of it simply send the data to PHP_SELF while mine send it to other file. It's kinda frustrating.

cust_form.php (which basically text) :

<form action = "cust_detail.php" method = "post">
    <table border="1">
        <tr>
            <td colspan = "2">
                <font size = "5">
                    Customer Details :
                </font>

                <br>

                <b>
                    #All fields are compulsory.
                </b>
        </tr>

        <tr>
            <td>
                New Customer Email :

            <td>
                <input name = "email"
                       size = "30"
                       type = "text">
        </tr>

        <tr>
            <td>
                Mobile Phone :

            <td>
                <input name = "tel"
                       type = "text">
        </tr>

        <tr>
            <td>
                First Name :
            <td>
                <input name = "fname"
                       type = "text">
        </tr>

        <tr>
            <td>
                Last Name :

            <td>
                <input name = "lname"
                       type = "text">
        </tr>

        <tr>
            <td>
                Identification / Passport Number :

            <td>
                <input name = "ic"
                       type = "text">
        </tr>

        <tr>
            <td>
                Address :

            <td>
                <textarea name = "address"
                          cols = "25"
                          rows = "2">
                </textarea>
        </tr>

        <tr>
            <td>
                City :

            <td>
                <input name = "city"
                       type = "text">
        </tr>

        <tr>
            <td>
                State :

            <td>
                <input name = "state"
                       type = "text">
        </tr>

        <tr>
            <td>Country:

            <td>
                <select name = "country">
                    <option name  = "default"
                            value = "default">
                        ----Please choose your
                    </option>
                </select>
        </tr>

        <tr>
            <td>
                Postal Code :

            <td>
                <input name = "code"
                       type = "text">
                    enter code here
        </tr>

        <tr>
            <td colspan = "2">
                <b>
                    <font size = "3">
                        <u>
                            INFO :
                        </u>
                    </font>

                    <br>

                    * Identification/passport number needed for verification during redemption on booth.

                    <br>

                    * For phone number, fill including International code (e.g. +601234567890)
                </b>
        </tr>

        <tr>
            <td align   = "right"
                colspan = "2">
                <button name = "submit"
                        type = "submit">
                    Submit
                </button>
        </tr>
    </table>
</form>

And for cust_details.php...

<?php
    include( 'global.php' );

    session_start();

    $fname   = '';
    $lname   = '';
    $email   = '';
    $address = '';
    $code    = '';
    $state   = '';
    $country = '';
    $tel     = '';
    $ic      = '';

    $fname_error = '';
    $lname_error = '';
    $tel_error   = '';
    $email_error = '';

     if( isset( $_POST[ 'submit' ] ) )
    {
        //validate first name
        if ( empty( $_POST[ 'fname' ] ) )
        {
            $fname_error = "First name is required";
            $_SESSION[ 'errormsg' ] = $fname_error;
        }
        else
        {
            if ( !preg_match( "/^[a-zA-Z]*$/",
                              $fname ) )
            {
                $fname_error = "Only letters and white space allowed.";
                $_SESSION[ 'errormsg' ] = $fname_error;
            }

            $fname = input_test( $_POST[ 'fname' ] );
        }

        //validate last name
        if ( empty( $_POST[ 'lname' ] ) )
        {
            $lname_error = "Last name is required";
            $_SESSION[ 'errormsg' ] = $lname_error;
        }
        else
        {
            if ( !preg_match( "/^[a-zA-Z]*$/",
                              $lname ) )
            {
                $lname_error = "Only letters and white space allowed.";
                $_SESSION[ 'errormsg' ] = $lname_error;
            }

            $lname = input_test( $_POST[ 'lname' ] );
        }

        //validate email
        if ( empty( $_POST[ 'email' ] ) )
        {
            $email_error = "Email is required";
            $_SESSION[ 'errormsg' ] = $email_error;
        }
        else
        {
            if ( !filter_var( $email,
                              FILTER_VALIDATE_EMAIL ) )
            {
                $email_error = "Invalid email";
                $_SESSION[ 'errormsg' ] = $email_error;
            }
            else
                $email = input_test( $_POST[ 'email' ] );
        }

        //validate phone no
        if ( empty( $_POST[ 'tel' ] ) )
        {
            $tel_error = "Phone number is required";
            $_SESSION[ 'errormsg' ] = $tel_error;
        }
        else
        {
            if ( preg_match( "/^[0-9-]+$/",
                             $tel ) )
            {
                $tel_error = "Invalid phone number";
                $_SESSION[ 'errormsg' ] = $tel_error;
            }

            $tel = input_test( $_POST[ 'tel' ] );
        }

        $address = input_test( $_POST[ 'address' ] );
        $country = input_test( $_POST[ 'country' ] );
        $code = input_test( $_POST[ 'code' ] );
        $state = input_test( $_POST[ 'state' ] );
        $ic = input_test( $_POST[ 'ic' ] );    

        if ( isset( $_SESSION[ 'errormsg' ] ) )
        {
            echo '############################################################\n\n';
            echo '<br><br><br>\n\n';
            echo $error = ( $_SESSION[ 'errormsg' ] ) .
                              '\n\n';

            unset ( $_SESSION[ 'errormsg' ] );

            echo '<br><br>\n\n';
            echo '############################################################\n";
        }
    }

    function input_test( $datatest )
    {
        $datatest = trim( $datatest );
        $datatest = stripslashes( $datatest );
        $datatest = htmlspecialchars( $datatest );

        return $datatest;
    }

    //send data
    $send_db = "INSERT INTO customer_details ( first_name,
                                               last_name,
                                               email,
                                               address,
                                               post_code,
                                               state,
                                               country,
                                               no_phone,
                                               ic )
                VALUES ( '$fname',
                         '$lname',
                         '$email',
                         '$address',
                         '$code',
                         '$state',
                         '$country',
                         '$tel',
                         '$ic' )";

    if ( $con -> query( $send_db ) === TRUE )
        echo "<br><br>Records inserted successfully\n";
    else
        echo "Error : " .
                 $con -> error;

    $con -> close();
?>
2
  • Just validate values/fields in cust_detail.php and show error(s) if they are present. If errors are present - do nothing with database...? Commented Apr 13, 2017 at 5:37
  • Yes, thats what I mean. If error(s) are present, it would simply prompt user to enter the correct value and prevent the incorrect data from been send to database. Commented Apr 13, 2017 at 6:05

3 Answers 3

1

1)How to validate the data before it been send to database?

PHP is a server side scripting language so if you want to validate the data at client side then you will have to use javascript. jQuery can make your life easier.

2)How to display the error. Either in cust_details.php or cust_form.php?

I can see that you have implemented that in your cust_details.php file. Is it not working?

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

2 Comments

i should edit the number 2 part. I mean how to display the error in cust_form.php and the incorrect data will not been send/save to database.
The best method is to merge both files into one. So you submit the form to the same script/file and at the top of the file you check for form submission and check if there is an error. If there is an error you can clear the post data for that variable and change the input fields to "<input type="text" name="email" size="30" value="<?= $_POST['email'] ?>"> . If data was posted and there was no error, then write to database and avoid the form output or redirect to another file.
1

html5 can check and validate and tell the user what is wrong with their input without needing to many php functions ,firstly if the field can't be empty then simply use the required attribute in input.

input type email checks that it is a email

<input type="email" name="email" required>

input type tel checks that it is a valid telephone number

<input type="tel" name="tel" required>

for names to check only abc you can use pattern attribute

<input type="text" name="fname" pattern="[a-zA-Z]+" required>

if you do all the checks in php then the pages have to reload before the user knows their input is wrong but if you do it in html the page doesn't reload which makes your website faster

3 Comments

for tel validation doesnt seem to work because eventhough i put alphabet in the field, its still validate it. The rest works perfectly.
if your browser does not support type="tel" it will fall back to type="text".
ah yes. pattern also can be applied to type="tel". Thank you. for future reference miketaylr.com/pres/html5/forms2.html
0

Since you are using the $_SESSION['errormsg'] variable to record the error messages you can just check if it is empty and continue to insert the data, else, display the error messages.

Although you are using $_SESSION['errormsg'] i would advice you to use a normal array like $_errors = array();. Set it up as an empty array and then keep on appending values of the errors to it for example by calling function addError() and passing it an error string.

public function addError($error)
    {
        $this->_errors[] = $error;
    }

If it is empty continue with the database, else, you just iterate through the whole array errors and list them to the user. For example,

if (empty($_errors)) {
     // array is empty, insert to database
}else{
     //array has error messages, display them
   }

Let me know if it helps or if you find a problem.

1 Comment

i will let you know if i managed to make this work. Thanks for the tips about array.

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.