douzhan1238
douzhan1238
2014-03-13 04:07
浏览 48
已采纳

使用PDO将数据插入MySQL数据库

I'm new to PHP and MySQL and I'm trying to insert data in to a database, which had worked fine until i attempted to use PDO's prepare method. It returns the catch error and i cannot figure out why - i'd also like to know whether it's best practice to use unnnamed placeholders or named placeholders?

The username and password variables are defined earlier in my code and catches data from the user using $_POST.

EDIT: getMessage() error displays SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'username' cannot be null

if (!empty($user) && (!empty($password)) ) {
    try {
        $results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)");
        $results->bindParam(1,$username);
        $results->bindParam(2,$password);
        $results->execute();
    } catch (Exception $e) {
        echo "Could not insert data in to the database";
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doufei6456
    doufei6456 2014-03-13 04:17
    已采纳

    You have two different variable names. You're checking $user to make sure it's not empty() but then you tell bind $username to the first parameter. You'll just need to rename one of them to match the other.

    点赞 评论
  • dongyi1490
    dongyi1490 2014-03-13 04:20

    Try this one.

    if (!empty($user) && (!empty($password)) ) {
    try {
        $results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)");
        $results->bindParam(1,$user);
        $results->bindParam(2,$password);
        $results->execute();
    } catch (Exception $e) {
        echo "Could not insert data in to the database";
    }
    

    }

    Please try yourself first to find the error.

    点赞 评论

相关推荐