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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵