doujia4619 2017-11-23 22:29 采纳率: 0%
浏览 118
已采纳

PHP表单验证不起作用

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";

?>
  • 写回答

2条回答 默认 最新

  • dsiuy42084 2017-11-23 22:47
    关注

    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! :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上