php / mysql表单验证问题

时间:2016-03-01 19:13:23

标签: php html mysql

所以我的php验证有两个检查功能,首先它检查一个空名称或密码条目,如果用户在输入他的名字时输入不需要的字符,则问题是如果用户输入了不需要的字符或数字'名称'表单仍然保存到数据库,它不应该保存到数据库,如果用户将名称和密码字段都留空并显示错误,则没有任何内容保存到数据库,这意味着我的验证检查的一半工作正常。任何人都可以帮助我吗?

<?php
// Connect to data base
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}   
// define variables and set to empty values
$nameErr = $userpasswordErr = "";
$name = $userpassword = "";
  //check for error 
if ($_SERVER["REQUEST_METHOD"] == "POST") {   
    //validate name and password
    if (
            empty($_POST["name"]) || 
            empty($_POST["userpassword"] || 
            !preg_match("/^[a-zA-Z ]*$/",$name))
    ) {
        $nameErr= "* Incorrect username or password ";   
    } else {
        $name = test_input($_POST["name"]);
        $userpassword = test_input($_POST["userpassword"]);

        $sql = "INSERT INTO users(name,email)
             VALUES ('$name','$userpassword')"; 
        if ($conn->query($sql) === true) {
           echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
        $conn->close();
    }
}     

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);

    return $data;
}

?>
<span class="error"></span>
<form method="post" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]);?>">
name : <input type="text" name="name" value="<?php echo $name;?>"/>
<span class="error"><?php echo $nameErr ;?> </span>
<br/><br/>
password :  <input type="text" name="userpassword" value="<?php echo $userpassword ; ?>">
<span class="error"><?php echo $userpasswordErr ;?> </span>
<br/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>

1 个答案:

答案 0 :(得分:0)

正则表达式检查中的$name应为$_POST['name']

if(empty($_POST["name"]) || empty($_POST["userpassword"] || !preg_match("/^[a-zA-Z ]*$/",$_POST["name"])))
{
     $nameErr= "* Incorrect username or password ";  
}