douzhi1972 2013-11-18 21:02
浏览 35

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

I've just started to learn OOP PHP and i'm trying create class that will do connection to my data base.

The code:

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

But I am getting this error:

 Fatal error: Call to undefined method DB_CONNECT::prepare();

What I understand is that the PDO object couldn't be created. Can you give some guidance please?

  • 写回答

2条回答 默认 最新

  • dongyuan9149 2013-11-18 21:14
    关注

    Learning OOP is not the reason for creating pointless classes.
    Unfortunately, you created one. PDO don't need a class to be built on top of it. Just leave it as is.

    So, instead of

    $db = new DB_CONNECT("localhost", "oopcms","viktor","viktor");
    

    make it

    $db = new PDO("localhost", "oopcms","viktor","viktor");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    that would be way clearer and useful

    评论

报告相同问题?

悬赏问题

  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法