doubu5035 2013-10-14 16:48 采纳率: 100%
浏览 41
已采纳

PDO:在哪里声明数据库连接?

I've just started using PDO and was wondering how best to declare the database connection?

Would it best practice to create a script as follows, called config.php for example

config.php

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

Then have example.class.php

<?php
include config.php;
class Example {
    public function fetch() {
          $data = $dbh->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($name));
          // do stuff
    }

}
?>

And do this for all my classes? Or would this make multiple connections? I want to have as few connections as possible.

  • 写回答

3条回答 默认 最新

  • dongshang1979 2013-10-14 16:54
    关注

    You're close but your fetch function won't work because $dbh is outside its scope.

    You could globalize it but a better solution is to pass your handler to your class upon instantiation

    class Example {
        /** @var \PDO */
        protected $pdo;
    
        public function __construct(\PDO $pdo) {
             $this->pdo = $pdo;
        }
    }
    $class = new Example($dbh);
    

    This is a best practice. This way the logistics of setting up and naming your db pointer are irrelevant. Your class defines how it's going to receive it and you use the instance of the pointer you were passed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办
  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了
  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch