【问题标题】:validation for form php mysql验证表单 php mysql
【发布时间】:2017-02-09 14:16:46
【问题描述】:

我有一个表单,用户可以向网站提交他们的信息和评论。但是,我在验证表单时遇到了问题。例如,我可以提交一个空表单并在我的名字中添加数字。按理说它应该是错误的并回显信息。但是,我仍然可以提交它,并且我的验证码不适用于该表单。 我的代码如下:

    <?php
error_reporting(~E_NOTICE); // avoid notice

require_once 'dbconfig.php';


if (isset($_POST['submitted'])) {
    $firstname  = $_POST['firstname'];//firstname
    $lastname = md5($_POST['lastname']);//password
    $phone = $_POST['phone']; // user name
    $enquiry  = $_POST['comment']; // user job


// Initialize error array.
    $errors = array();
    // Check for a proper First name
    if (!empty($_POST['firstname'])) {
        $firstname = $_POST['firstname'];
        $pattern = "/^[a-zA-Z0-9\_]{2,20}/"; // This is a regular expression that checks if the name is valid characters
        if (preg_match($pattern, $firstname)) {
            $firstname = $_POST['firstname'];
        } else {
            $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';
        }
    } else {
        $errors[] = 'You forgot to enter your First Name.';
    }

    // Check for a proper Last name
    if (!empty($_POST['lastname'])) {
        $lastname = $_POST['lastname'];
        $pattern = "/^[a-zA-Z0-9\_]{2,20}/"; // This is a regular expression that checks if the name is valid characters
        if (preg_match($pattern, $lastname)) {
            $lastname = $_POST['lastname'];
        } else {
            $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';
        }
    } else {
        $errors[] = 'You forgot to enter your Last Name.';
    }

    //Check for a valid phone number
    if (!empty($_POST['phone'])) {
        $phone = $_POST['phone'];
        $pattern = "/^[0-9\_]{7,20}/";
        if (preg_match($pattern, $phone)) {
            $phone = $_POST['phone'];
        } else {
            $errors[] = 'Your Phone number can only be numbers.';
        }
    } else {
        $errors[] = 'You forgot to enter your Phone number.';
    }
    if (!empty($_POST["comment"])) {
        $comment = $_POST['comment'];
    } else {
        $errors[] = 'You forgot to enter your enquiry infomation.';
    }
    // if no error occured, continue ....
    if (!isset($errMSG)) {
        $stmt = $DB_con->prepare('INSERT INTO user_message(firstname,lastname,phone,enquiry) VALUES(:fstname, :lastname, :phone, :enq)');
        $stmt->bindParam(':fstname', $firstname);
        $stmt->bindParam(':lastname', $lastname);
        $stmt->bindParam(':phone', $phone);
        $stmt->bindParam(':enq', $enquiry);


        if ($stmt->execute()) {
            $successMSG = "enquiry succesfully submitted ...";
            header("refresh:5;contactus.php"); // redirects image view page after 5 seconds.
        } else {
            $errMSG = "error while inserting....";
        }
    }
}
/////////////////////////////////////////////////////////////////////////////////////////

?>

<!DOCTYPE html>
<html>
    <head>
        <title>Boostrap 3 example</title>
        <meta charset="UTF-8">
        <meta name="viewpoint" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="bootstrap3/css/bootstrap.min.css">
              <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>

        <link href="css/maincss.css" rel="stylesheet" type="text/css"/>

    </head>

    <body>
        <div class="container">
            <?php
            if (isset($errMSG)) {
                ?>
                <div class="alert alert-danger">
                    <span class="glyphicon glyphicon-info-sign"></span> <strong><?php echo $errMSG; ?></strong>
                </div>
                <?php
            } else if (isset($successMSG)) {
                ?>
                <div class="alert alert-success">
                    <strong><span class="glyphicon glyphicon-info-sign"></span> <?php echo $successMSG; ?></strong>
                </div>
                <?php
            }
            ?>  
            <h2>Contact us</h2>
            <br/>
            <p>Fill out the form below.</p>
            <p>* required field.</p>
            <form method="post" enctype="multipart/form-data" class="form-horizontal">
                <table class="table table-bordered table-responsive">
                    <tr> 
                        <td><label >First Name*:</label></td>
                        <td><input name="firstname" type="text" value="" /></td>
                    </tr>
                    <tr> 
                        <td><label >Last Name: </label></td>
                        <td><input name="lastname" type="text" value="" /></td>
                    </tr>
                    <tr> 
                        <td><label >Phone Number: </label></td>
                        <td><input name="phone" type="text" value="" /></td>
                    </tr>
                    <tr> 
                        <td><label >Enquiry: </label></td>
                        <td><textarea name="comment" rows="5" cols="40"></textarea></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <input name="" type="reset" value="Reset Form" /> 
                            <button type="submit" name="submitted" class="btn btn-default">Create</button><br/>

                        </td>
                    </tr>

                </table>
            </form>
        </div>
        <script src="js/jquery-1.12.3.js"></script>
        <script src="bootstrap3/js/bootstrap.js"></script>       
    </body>
</html>

这是我的数据库设计:

【问题讨论】:

  • 如果您使用 HTML5,您可以将required 属性添加到您的input-tags。
  • 对于名称你应该使用像这样的正则表达式/^[A-z]+$/,因为你只需要字母
  • @stackoverflowuser - 有些人有使用空格或连字符的双重名称。而且很多人的字符不是a-z。在名称方面,您不能非常严格,否则您可能会疏远很多用户。但是,当前的验证是错误的。它确实允许数字名称和_,我从未见过有人以他们的名字命名?
  • @Magnus Eriksson 是的,我的错,我只是很快就写了这个验证,没有多想。然而,这个主题的一些验证应该可以完成这项工作。 link 或者,正如你之前提到的,只检查长度。

标签: php mysql forms validation


【解决方案1】:

问题 1

您使用错误消息填充了一个名为$errors 的数组,但随后您检查了$errMSG。永远不会设置该变量。改为:

if (!$errors) {
    // your database code

如果发生任何错误,这应该会阻止它插入任何内容。

问题 2

您的正则表达式允许任何字母字符和/或数值和/或下划线,只要它的长度在 2 到 20 个字符之间,这意味着:aaaaaaaaaaaa、1111111、_______ 都被认为是有效的名字。

验证姓名很棘手,因为有些人的字符在 a-z(外名)之外,还有带有空格、破折号、撇号等的双名。我建议简单地检查姓名的长度,例如:

if (strlen(trim($firstname)) >= 2 || strlen(trim($firstname)) <= 20) {
    // .... ok
} else {
    // .... error
}

注意:我不会将 20 作为最大长度。您的 DB 列的长度为 100,因此.. 至少允许这样做。不要以为每个人都有惯用的名字。

问题 3

一开始,您填充$enquiry = $_POST['comment']。稍后,您可以:$comment = $_POST['comment'],然后在数据库插入中使用$enquiry。

您可能还有更多可以解决的问题,但这些是最突出的,也是您问题中问题的根源。

【讨论】:

  • 谢谢!!该代码现在可以工作,但我不太确定如何将问题 2 解决方案应用于我的代码。你可以扩展一下吗?
  • 只需替换您的if (preg_match(....))。如果此答案解决了您的问题,请随时将其标记为已回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
相关资源
最近更新 更多