在第46行的crud.class.php中调用null上的成员函数prepare()

时间:2017-01-06 21:08:46

标签: php mysql pdo

我不知道为什么会出现这个错误,我正在尝试使用PDO调用一个prepare方法,但它给了我错误

这是我的代码:

        public function create($user,$db){
        $return_array = array("success"=>true,"message"=>"");
        $create_user = new User("", "", "", "");
        //validate the user
        $validation = new Validation();
        /*if(!$validation->username($user->getUsername())){
            $return_array['success'] = false;
            $return_array['message'] = $validation->get_username_criteria()."\n";
            echo $return_array['message'];
        }
        if(!$validation->password($user->getPassword())){
            $return_array['success'] = false;
            $return_array['message'] = $validation->get_password_criteria()."\n";
            echo $return_array['message'];
        }*/
        if($return_array['success']){
            $insert_query = "INSERT INTO 'user' ('username', 'password', 'level')VALUES (:username, :password, :level)";
            $stmt = $this->db->prepare($this->insert_query);
            $stmt->bindValue(":username", $create_user->getUsername(), PDO::PARAM_STR);
            $stmt->bindValue(":password", $create_user->getPassword(), PDO::PARAM_STR);
            $stmt->bindValue(":level", $create_user->getLevel(), PDO::PARAM_INT);
            $stmt->bindValue(":id", $id, PDO::PARAM_INT);
            $stmt->execute();
            echo "lalala";
            return $return_array;

        }
        else
        {
            echo "lululu";
            return $return_array;

        }
    }

这是我与数据库的连接:

class Database{
private $DB_USER="";
private $DB_PASS="";
private $DB_NAME="";
private $DB_HOST="";

private $db;



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

public function get_db(){
    return $this->db;
}

public function _destruct(){
    $this->db = null;
}

这里我调用方法create():

$username = $_POST['username'];
$password = $_POST['password'];
$level = $_POST['level'];
$id = $_POST['id']; 
$user = new User($id,$username,$password,$level);
$crud_obj = new crud();
$db_obj = new Database();
if($crud_obj->create($user,$db_obj->get_db())){
    echo "Successfully registered!";
}

0 个答案:

没有答案