也许这是一个可能的重复,我在这里搜索一些这样的问题,但我已经尝试了所有的答案,但我仍然有这个错误
Notice: Undefined property: User::$_pdo in D:\xampp\htdocs\pengun\classes\DB.php on line 32
和此错误
Fatal error: Call to a member function prepare() on a non-object in D:\xampp\htdocs\pengun\classes\DB.php on line 32
这是我的DB类
<?php
class DB {
private $_pdo, $_query, $_result, $_count, $_row;
public function __construct($host, $dbname, $user, $password) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->dbname = $dbname;
try {
$_pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname, $this->user, $this->password);
} catch (PDOException $e) {
die($e->getMessage());
}
$_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function select($fields, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=','>','<','>=','<=');
$column = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "SELECT {$fields} FROM {$table} WHERE {$column} {$operator} {$value}";
if($this->_query = $this->_pdo->prepare($sql)) {
$this->_query->execute();
$this->_row = $this->_query->fetch();
print_r($this->_row);
}
}
}
}
}
有人可以告诉我我的代码有什么问题吗?提前谢谢。
答案 0 :(得分:1)
因为在构造函数中,您只将new PDO
分配给只能在构造函数内部访问的局部变量。你必须使用:
$this->_pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname, $this->user, $this->password);
...
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
答案 1 :(得分:0)
您在构造函数中为PDO
对象分配了局部变量。你必须设置类变量!
更改
$_pdo
到
$this->_pdo
第13和18行。