PDO仅插入插入一些数据

时间:2015-09-22 01:32:48

标签: php mysql pdo

以下代码仅将数据插入“email”和“password”字段,将0插入角色(这很好)。名字和姓氏字段为空。我无法弄清楚原因。

我的数据库有:id,fname,lname,email,role,password

我尝试了许多不同的解决方案,一直在撞墙。我能够发现$ fname和$ lname似乎没有绑定或插入,但如果我在脚本的顶部回显它们,它们就会被识别出来。

<?
require_once('connection.php');

if (isset($_POST['submit'])) {
    $errMsg = '';
    //username and password sent from Form
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $fname = trim($_POST['fname']);
    $lname = trim($_POST['lname']);
    if ($email == '' or $password == '' or $email == '' or $fname = '' or $lname = '')
        $errMsg = 'All Fields Are Required.<br>';

    if ($errMsg == '') {
        $sql = "SELECT COUNT(email) AS num FROM users WHERE email = :email";
        $stmt = $databaseConnection->prepare($sql);
        $stmt->bindValue(':email', $email);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row['num'] > 0) {
            die('That email address already exists! <a href=\"register.php\">Please try again.</a>');
        }
        $passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
        $stmt = $databaseConnection->prepare("INSERT INTO users (fname, lname, email, password) VALUES (:fname, :lname, :email, :password)");
        $stmt->bindValue(':fname', $fname);
        $stmt->bindValue(':lname', $lname);
        $stmt->bindValue(':email', $email);
        $stmt->bindValue(':password', $passwordHash);

        $result = $stmt->execute();
        if ($result) {
            header('Location:index.php');
            echo 'User created.  Please log in.';
            die();
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Register</title>
</head>
<body>

<div align="center">
<div style="width:300px; border: solid 1px #006D9C; " align="left">

<?php
if (isset($errMsg)) {
    echo '<div style="color:#FF0000;text-align:center;font-    size:12px;">'.$errMsg.'</div>';
}
?>
<div style="background-color:#006D9C; color:#FFFFFF; padding:3px;"><b>Register</b></div>
<div style="margin:30px">
<form action="" method="post">
<label>First Name  :</label><input type="text" name="fname" class="box"/><br /><br />
<label>Last Name  :</label><input type="text" name="lname" class="box"/><br /><br />
<label>Email  :</label><input type="email" name="email" class="box"/><br /><br />
<label>Password  :</label><input type="password" name="password" class="box" /><br/><br />
<input type="submit" name='submit' value="Submit" class='submit'/><br />
</form>
</div>
</div>
</div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

实际上,您实际上是将null赋给fname和lname变量,而不是比较null:

if($email == '' or $password=='' or $email=='' or $fname='' or $lname='')

请使用

  

==

而不是

  

=