简体   繁体   中英

PHP form validation doesn't work

I'm all new to PHP and JavaScript, just learning web development and I'm trying all sort of things in my free time, however, there is one thing I cannot find a solution for. I have a form that would be collecting only 4 datas, Name, Date of Birth, Email and Phone number. All fields are required for further data procession. I literally tried every single thing I found on Google, but it still doesn't work. The form simply saves all sort of data into the database, without checking the input fields.

Later on I'd like the code to validate the form, display any errors on the same page not on a different ".php" one and also send 2 emails one as a confirmation for the person and one for notifying me about a form submission. What should I do/change to achieve that? I feel quite stuck atm.

my form:

<form class="contactform" id="cfrm" action="process.php" method="post">
    <div class="f-data">
        <input class="f-error" name="uname" placeholder="NAME" type="text" required="required" data-error="Name is required.">
    </div>
    <div class="clear"></div>
    <div class="f-data">
        <select name="birthday" id="forminput" aria-required="true" aria-invalid="false">
            <option value="11">11</option>
            <option value="12">12</option>
        </select>
        <select name="birthyear" id="forminput" aria-required="true">
            <option value="1900" selected="selected">1900</option>
            <option value="2001">2001</option>
        </select>
    </div>

    <div class="f-data">
        <input class="f-error" name="uemail" placeholder="EMAIL" type="text" required="required" data-error="Email is required.">
    </div>

    <div class="f-data">
        <input class="f-error" name="uphone" placeholder="PHONE" type="text" required="required" data-error="Phone is required.">
    </div>

    <div class="clear"></div>

    <div class="submit">
        <p>
            <input type="submit" value="submit" name="submit">
        </p>
    </div>

and the process.php

<?php

require "connection.php";
require "others/phpmailer/PHPMailerAutoload.php";

//form data
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$Name = $connection->real_escape_string($_POST['uname']);
$DoB = $connection->real_escape_string($_POST['birthyear'] . '-' . 
$_POST['birthmonth'] . '-' . $_POST['birthday']);
$inputDoB = date("Y-m-d",strtotime($DoB));
$Email = $connection->real_escape_string($_POST['uemail']); 
$Phone = $connection->real_escape_string($_POST['uphone']);

if (strlen($agree) == 0) $agree = 0;

// validating
if(isset($_POST['submit']));
{ 
    if(empty($_POST['uname']))
    {  
        $msg_name = "You must enter name";  
        $name_subject = $_POST['uname'];  
        $name_pattern = '/^[a-zA-Z ]*$/';  
        preg_match($name_pattern, $name_subject, $name_matches);  
        if(!$name_matches[0])  
            $msg2_name = "Only alphabets and white space allowed";  
        }

        if(empty($_POST['uemail']))
        { 
            $msg_email = "You must enter your email";  
            $email_subject = $_POST['uemail'];  
            $email_pattern = '/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/';  
            preg_match($email_pattern, $email_subject, $email_matches);  
            if(!$email_matches[0]) $msg2_email = "Must be a valid email address";
        }  

        if($_POST['uphone'])  
        {  
            $phone = $_POST['uphone'];  
            preg_match('/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z {2,3})$/i', $phone, $phone_match);  
            if(!$phone_match[0]) $msg_phone = "Must be a valid phone number";   
            if(strlen($phone)!='8') $msg2_phone = "Must be at least 8 characters long";  
        }  
    }
    //save to db
    $query = "INSERT INTO form (Name,DoB,Email,Phone,Date) VALUES ('$Name','$DoB','$Email','$Phone', CURRENT_TIMESTAMP)";

    $success = $connection->query($query);

    if (!$success) {
        die("Couldn't enter data: ".$connection->error);
    }

    echo "Thank You For Contacting Us";

?>

As for your display of inline error messages, what I would recommend doing is only making use of one page to handle the main form 'logic', and another include() to represent the raw HTML markup fo the form itself. The 'logic' page would be where you direct your visitors as the 'form'.

Inside of your if(isset($_POST['submit'])) , you would check the data that is submitted. If it is valid, you go ahead and process the submission. If it is invalid, you raise an error, and show the form again. The form is also shown by default.

This is shown in the following semi-pseudocode:

$error = ''; // Nothing is wrong at first
if(isset($_POST['submit'])) {
  // Raise error messages based on submission
  if(empty($_POST['uname'])) {  
    $error = "You must enter name";
  }
  if(empty($_POST['email'])) {  
    $error = "You must enter email";
  }

  // Show the form if there are errors
  if ($error) {
    include('form.php');
  }
  // Process the submission if there aren't
  else {
    //$query = ...
    mail($Email, $email_subject, $msg_email);
  }
}
else {
  include('form.php');
}

With form.php conditionally checking for $error :

<?php
if ($error !== '') {
  // Output the error message in a fancy way
  echo "<span class='error'>" . $error . "</span>";
}
?>
<form> ... </form>

As for sending the two emails, you're practically there! You already have $msg_email , $email_subject and $Email . You're just looking to make use of PHP's mail() function:

mail($Email, $email_subject, $msg_email);

Note that you'll probably want to add the fourth parameter (headers) in there as well.

I also note that you currently have a semicolon in if(isset($_POST['submit']));{ , which will prevent the block from triggering. Make sure you remove this.

Hope this helps! :)

While formatting your code for question clarity I think I found the issue.

You have 2 formatting issues that would cause this sort of issue.

1) You have a semicolon preventing your if from being a block conditional

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

with that semicolon there the block will run separated and simply act as a scope separator.

2) Your Regex isn't complete

preg_match('/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z {2,3})$/i', $phone, $phone_match);  

In your last capture group (.[az {2,3}) you don't have a closing square bracket for the [az] character selector it should be (.[az]{2,3})

I would also point out that you are setting $msg_name and $msg2_name but I don't see them used anywhere and you don't stop execution on error so the process just continues through to the query even though you said you want it to stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM