【问题标题】:PHP SQL Form validationPHP SQL 表单验证
【发布时间】:2012-05-31 13:57:59
【问题描述】:

我想制作一个简单的表单,如果没有输入字段,它会显示错误。我不知道该怎么做。这是我的代码: php代码:

<?php

    //include the connection file

    require_once('connection.php');

    //save the data on the DB and send the email

    if(isset($_POST['action']) && $_POST['action'] == 'submitform')
    {
        //recieve the variables

        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $ip = gethostbyname($_SERVER['REMOTE_ADDR']);

        //save the data on the DB

        mysql_select_db($database_connection, $connection);

        $insert_query = sprintf("INSERT INTO feedback (name, email, message, date, ip) VALUES (%s, %s, %s, NOW(), %s)",
                                sanitize($name, "text"),
                                sanitize($email, "text"),
                                sanitize($message, "text"),
                                sanitize($ip, "text"));

        $result = mysql_query($insert_query, $connection) or die(mysql_error());

        if($result)
        {
            //send the email

            $to = "abc@xyz.com";
            $subject = "New message from the website";

            //headers and subject
            $headers  = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
            $headers .= "From: ".$name." <".$email.">\r\n";

            $body = "New contact<br />";
            $body .= "Name: ".$name."<br />";
            $body .= "Email: ".$email."<br />";
            $body .= "Message: ".$message."<br />";
            $body .= "IP: ".$ip."<br />";

            mail($to, $subject, $body, $headers);

            //ok message

            echo "Your message has been sent";
        }
    }

    function sanitize($value, $type) 
    {
      $value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value;

      switch ($type) {
        case "text":
          $value = ($value != "") ? "'" . $value . "'" : "NULL";
          break;    
        case "long":
        case "int":
          $value = ($value != "") ? intval($value) : "NULL";
          break;
        case "double":
          $value = ($value != "") ? "'" . doubleval($value) . "'" : "NULL";
          break;
        case "date":
          $value = ($value != "") ? "'" . $value . "'" : "NULL";
          break;
      }

      return $value;
    }
    ?>

<form id="ContactForm" method="post" action="mail.php">
                            <div class="wrapper"><input class="input" name="name" id="name" type="text" value="Name:" onBlur="if(this.value=='') this.value='Name:'" onFocus="if(this.value =='Name:' ) this.value=''" ></div>
                            <div class="wrapper"><input class="input" name="email" id="email" type="text" value="E-mail:" onBlur="if(this.value=='') this.value='E-mail:'" onFocus="if(this.value =='E-mail:' ) this.value=''" ></div>
                            <div class="textarea_box"><textarea cols="1" rows="1" onBlur="if(this.value=='') this.value='Message:'" onFocus="if(this.value =='Message:' ) this.value=''" >Message:</textarea></div>
                            <input type="hidden" id="action" name="action" value="submitform" />
                            <input type="submit" class="button" id="submit" name="submit" value="Submit" /> <input type="reset" class="button" id="reset" name="reset" value="Reset" />
                        </form>

【问题讨论】:

  • 您可以在服务器端使用 php 验证您的表单,但我建议在提交表单之前使用 javascript/jQuery 验证表单输入,然后使用 PHP 检查服务器端。有大量的 jQuery 表单验证插件,使其非常简单易行。
  • @martincarlin87 好吧,我更喜欢在服务器端进行检查。因为不是每个客户端都启用了 javascript...
  • 是的,但正如我所说,你可以同时做。

标签: php sql forms


【解决方案1】:

在将信息保存到数据库之前,请检查每个提交的值是否包含有效数据。如果没有,请将字段名称放入数组中。验证完成后,检查数组是否为空。如果它为空,请将信息保存到您的数据库中。如果已填充,则重新显示表单,填充提交的数据,并以易于阅读的方式告知他们所犯的错误,以便他们知道要修复什么。

需要研究的一些 PHP 函数是:filter_var()、ctype_* 和 empty()

仅供参考,您应该考虑从 they will soon be going away. 之后迁移出 mysql_* 函数

【讨论】:

    【解决方案2】:

    要实现这一点,您应该创建一个执行空检查的代码块(因为这是您要检查的唯一内容)。 下面给出一个简单的代码sn-p:

    function checkFormErrors($name,$email,$message){
        //now we define a function to check for errors
        $errors = array();
        //define an error container
        if(empty($name)){
            //check the name field
            $errors[] = "You need to enter a name";
        }
        if(empty($email)){
            //check the email field
            $errors[] = "You need to enter an email address";
        }
        .... //do more checks for all fields here
        return $errors;
    }
    if(isset($_POST['action']) && $_POST['action'] == 'submitform'){
        //recieve the variables
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $ip = gethostbyname($_SERVER['REMOTE_ADDR']);
    
        $errors = checkFormErrors($name,$email,$message);
        //check for errors
        if(empty($errors)){
            //continue with the processing you did above
            .....
        }
    }
    
    
    In you HTML file/page, you then need to put this above the form (feel free to style it
    with css)
    <?php
        if(isset($errors)){
            //the variable exists
            echo implode("<br />", $errors);
        }
    ?>
    

    我发表了一篇博文 here 并且还有一些脚本可以帮助进行表单验证

    希望这会有所帮助!

    【讨论】:

    • 到目前为止,表单一直在工作。我已经更改了表单以避免 SQL 注入并对其进行了大量编辑(来自各种博客和来源)。但现在我想在 md5 中编码密码。我正在尝试添加“md5 ['password']”,但它显示错误。我的php代码是:
    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 2019-04-01
    • 2013-11-16
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多