带有PDO语句的数据库连接类


Data Base Connection Class with PDO statement

我刚刚开始学习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对象无法创建。你能给我一些指导吗?

学习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);

这将是更清晰和有用的

感兴趣的人是这个问题的解决方案,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);