PDO lastInsertid()返回false,即使我的查询运行良好。提供0000码错误

时间:2018-07-05 21:36:54

标签: php pdo

这是我的代码,我正在尝试使用PDO将数据插入数据库,我不知道我的代码出了什么问题,那不是在lastInsertId()上插入并返回false。看一下我的代码:

Model.php

<?php
abstract class Model{
protected $dbh;
protected $stmt;

    public function __construct(){
        $this->dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
     }

     public function error(){
        print_r($this->dbh->errorInfo());
     }

     public function query($query){
       $this->stmt = $this->dbh->prepare($query);
     }

    //Binds the prep statement
    public function bind($param, $value, $type = null){
      if (is_null($type)) {
          switch (true) {
              case is_int($value):
                  $type = PDO::PARAM_INT;
                  break;
              case is_bool($value):
                  $type = PDO::PARAM_BOOL;
                  break;
              case is_null($value):
                  $type = PDO::PARAM_NULL;
                  break;
              default:
                  $type = PDO::PARAM_STR;
       }
      }
      $this->stmt->bindValue($param, $value, $type);
  }

   public function execute(){
      return $this->stmt->execute();
   }

    public function resultset(){
       $this->execute();
       return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function lastInsertId(){
        return $this->dbh->lastInsertId();
    }

    public function single(){
        $this->execute();
        return $this->stmt->fetch(PDO::FETCH_ASSOC);
    }

    }

注册功能:(这是我插入查询所在的注册功能)。

public function register(){

    $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    $pass = md5($post['password']);
    if(isset($post['submit']))
    {
        $this->query('INSERT INTO tbl_users (firstname, lastname, email, password, gender, dob) VALUES(:firstname, :lastname, :email, :password, :gender, :dob)');
        $this->bind('firstname', $post['fname']);
        $this->bind('lastname', $post['lname']);
        $this->bind('email', $post['email']);
        $this->bind('password', $pass);
        $this->bind('gender', $post['gender']);
        $this->bind('dob', $post['date']);
        $this->execute();

        if($this->lastInsertId()){
            header('Location:'.ROOT_PATH.'admin/user');
        }else{
            echo "wrong";
            $this->error();
        }
    }
}

有人可以告诉我我做错了什么,为什么会发生这种情况,我们将不胜感激。预先谢谢你。

1 个答案:

答案 0 :(得分:0)

问题已解决。这是导致该问题的我的数据库字段之一。我将NULL设置为no,也没有给出任何默认值,这导致了错误。我通过替换model.php中的代码发现了这一点:

$this->dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);

与此:

$options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
$this->dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS, $options);