我刚开始学习OOP PHP,我正在尝试创建类,它将连接到我的数据库。
代码:
class DB_CONNECT
{
private $host ;
private $dbName ;
private $userName ;
private $password;
private $db;
public function __construct($host,$dbName,$userName,$password){
$this->host = $host;
$this->dbName = $dbName;
$this->userName = $userName;
$this->password = $password;
try {
$this->db = new PDO('mysql:host='.$this->host.';dbname='.$this->dbName.';charset=utf8',$this->userName,$this->password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->db;
} catch (Exception $e) {
ECHO $e->getMessage();
}
}
}
$db = new DB_CONNECT("localhost", "oopcms","viktor","viktor");
function select($db){
$query = $db->prepare("SELECT * FROM `test`");
$query->execute();
$row = $query->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
$x = select($db);
var_dump($x);
但是我收到了这个错误:
Fatal error: Call to undefined method DB_CONNECT::prepare();
我的理解是无法创建PDO对象。你能指点一下吗?
答案 0 :(得分:1)
学习OOP不是创建无意义类的原因 不幸的是,你创建了一个。 PDO不需要在其上构建类。请保持原样。
所以,而不是
$db = new DB_CONNECT("localhost", "oopcms","viktor","viktor");
制作
$db = new PDO("localhost", "oopcms","viktor","viktor");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
这将更加清晰和有用
答案 1 :(得分:0)
感兴趣的是这个和 Pekka 和你的常识的解决方案,谢谢您提示:)
class Select
{
private $query;
private $dbh;
private $row;
public function __construct(){
$this->dbh = new DB_CONNECT("localhost", "oopcms","viktor","viktor");
}
public function select(){
$this->query = $this->dbh->db->prepare("SELECT * FROM `test`");
$this->query->execute();
$this->row = $this->query->fetchAll(PDO::FETCH_ASSOC);
return $this->row;
}
}
$sel = new Select();
$s = $sel->select();
var_dump($s);