无法使用PDO将数据插入数据库

时间:2014-04-23 22:12:23

标签: php mysql database pdo

我已经为注册页面编写了这段代码,但是我无法使用PDO将数据插入到我的数据库中(或者做错了事)。这是注册页面代码:

<?php
if (empty($_POST)){

?>
 <form name="registration" action="register.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label> 
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php 
}
else{
    $form = $_POST;
    $username = $form['username'];
    $password = $form['passowrd'];
    $fname = $form['fname'];
    $lname = $form['lname'];
    $email = $form['email'];
    $user = 'root';
    $pass = 'pdt1848!';

    $db = new PDO('mysql:host=localhost;dbname=phpproject', $user, $pass);


    $sql = "INSERT INTO users (username, password, fname, lname, email)VALUES(:username, :password, :fname, :lname, :email)";
    $query = $db->prepare($sql);
    $result = $query->execute(array(':username'=>$username, ':password'=>$password, 
            ':fname'=>$fname, ':lname'=>$lname, ':email'=>$email));

    if ($result){
        echo "Thanks for registering with us!";
    } else {
        echo "Sorry, an error occurred while editing the database. Contact the guy who built this garbage.";
    };

};
?>

3 个答案:

答案 0 :(得分:2)

错误就在这里,passowrd

$password = $form['passowrd'];

仅仅是一个错字。

将其更改为:

$password = $form['password'];

当一个失败时,整个查询都会失败。

如果您的代码中出现错误报告,它会立即将其提取出来。

您将来可以使用的方法是try & catch方法,例如:

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

以及

error_reporting(E_ALL);
ini_set('display_errors', 1);

您可以参考的链接以供进一步阅读:

PDO

的MySQL

(更多)


<强>密码

我还注意到您以纯文本格式存储密码。不建议这样做。

使用以下其中一项:

其他链接:

答案 1 :(得分:0)

我做这样的事情,

$user = 'your username';
$pass = 'your pass';
$db = new PDO( 'mysql:host=localhost;dbname=your_data_base_name', $user, $pass );
/*Grab Post*/
$form = $_POST;
$username = $form[ 'username' ];
$password = $form[ 'password' ];
$first_name = $form[ 'first_name' ];
$surname = $form[ 'surname' ];
$address = $form[ 'address' ];
$email = $form[ 'email' ];
// Sql
$sql = "INSERT INTO users ( username, password, first_name, surname, address, email )      VALUES ( :username, :password, :first_name, :surname, :address, :email )";

$result = $query->execute( array( ':username'=>$username, ':password'=>$password, ':first_name'=>$first_name, ':surname'=>$surname, ':address'=>$address, ':email'=>$email ) );

if ( $result ){
   echo "Thank you. You have been registered";
} else {
   echo "Sorry, there has been a problem inserting your details.";
}

此外,我总是按照Tuga的建议启用我的错误报告。它永远不会让我失望。

答案 2 :(得分:0)

passowrd中的拼写错误外,您应该为PDO启用异常,并使用try和catch语句来捕获异常。还有一些其他的小改动,比如首先构造PHP并删除POST超全局的奇数重新分配。

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){

    $result = "Thanks for registering with us!";
    try{
        $db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);


        $sql = "INSERT INTO users (username,   password,  fname,  lname,  email)
                            VALUES(:username, :password, :fname, :lname, :email)";
        $query = $db->prepare($sql);
        $query->execute(array(':username'=>$_POST['username'],
                              ':password'=>$_POST['password'],
                              ':fname'=>$_POST['fname'],
                              ':lname'=>$_POST['lname'],
                              ':email'=>$_POST['email']));
    }catch(PDOException $e){
        $result = 'Sorry, an error occurred while editing the database. Contact the guy who built this garbage.';
        //or use $e->getMessage(); for the real error
    }

    echo $result;

}
else{ ?>
<form name="registration" action="register.php" method="POST">
    <label for "username">Username: </label>
    <input type="text" name="username"/><br />
    <label for "password">Password: </label>
    <input type="password" name="password"/><br />
    <label for "fname">First Name: </label>
    <input type="text" name="fname"/><br />
    <label for "lname">Last name: </label> 
    <input type="text" name="lname"/><br />
    <label for "email">Email: </label>
    <input type="text" name="email"/><br />
    <button type="submit">Submit</button>
</form>
<?php } ?>

在您的数据库中存储纯文本密码也是一个非常糟糕的主意。〜阅读:Best way to store password in database.

编辑,

添加了一些输入验证,以帮助您入门,希望它有所帮助。未经测试。

<?php
try{
    $db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch(PDOException $e){
    die('Sorry, an error occurred while editing the database. Contact the guy who built this garbage.');
    //or use $e->getMessage(); for the real error
}


if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    //create empty error array - to fill with errors if any
    $error = array();

    //validate username
    if(empty($_POST['username'])){
        $error['username'] = 'Enter a username';
    }elseif(strlen($_POST['username']) <= 2){
        $error['username'] = 'Username too short > 2 chars';
    }else{
        //check for existing user
        $sql = "SELECT 1 
                FROM `users` 
                WHERE username = :username";

        $query = $db->prepare($sql);
        $query->execute(array(':username' => $_POST['username']));

        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        if(!empty($result)){
            $error['username'] = 'User already exists'; 
        }
    }

    //validate pass
    if(empty($_POST['password'])){
        $error['password'] = 'Please enter password';
    }elseif(strlen($_POST['password']) < 6){
        $error['password'] = 'Password too short, password should be 6 chars or longer';
    }

    //validate fname
    if(empty($_POST['fname'])){
        $error['fname'] = 'Please enter your first name';
    }

    //validate fname
    if(empty($_POST['lname'])){
        $error['lname'] = 'Please enter your last name';
    }


    //validate email
    if(empty($_POST['email'])){
        $error['email'] = 'Please enter your email';
    }else{
        if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            $error['email'] = 'Please enter valid email';   
        }
    }

    //no errors detected so insert
    if(empty($error)){
        $sql = "INSERT INTO users (username,   password,  fname,  lname,  email)
                            VALUES(:username, :password, :fname, :lname, :email)";
        $query = $db->prepare($sql);
        $query->execute(array(':username'=>$_POST['username'],
                             ':password'=>$_POST['password'],
                             ':fname'=>$_POST['fname'],
                             ':lname'=>$_POST['lname'],
                             ':email'=>$_POST['email']));

        $result = 'Thanks for registering with us! <a href="login.php">Click here to login</a>';
    }else{
        $result = 'Please correct the errors';
    }

}?>

<?php echo isset($result) ? $result : null;?>

<form name="registration" action="register.php" method="POST">
    <label for "username">Username: <?php echo isset($error['username']) ? $error['username'] : null;?></label>
    <input type="text" name="username"/><br />
    <label for "password">Password: <?php echo isset($error['password']) ? $error['password'] : null;?></label>
    <input type="password" name="password"/><br />
    <label for "fname">First Name: <?php echo isset($error['fname']) ? $error['fname'] : null;?></label>
    <input type="text" name="fname"/><br />
    <label for "lname">Last name: <?php echo isset($error['lname']) ? $error['lname'] : null;?></label> 
    <input type="text" name="lname"/><br />
    <label for "email">Email: <?php echo isset($error['email']) ? $error['email'] : null;?></label>
    <input type="text" name="email"/><br />
    <button type="submit">Submit</button>
</form>