douwen5985 2013-11-16 14:54
浏览 27
已采纳

与PDO和Singleton类的数据库连接

I'm trying to establish a database connection with PDO and a Singleton class but I'm having trouble fetching data from the database.

I've been reading up on this but I'm still not sure how to call the Singelton class in my database file from another file and get the results printed out. The error I'm getting right now is Fatal error: Call to undefined function query() in my db.php file, which is the last function in my database file. However I believe the function is defined.

Any help is appreciated!

Here is my database (db.php) connection file:

<?php
class Database 
{
    private $_db;
    static $_instance;

    private function __construct() {
        $this->_db = new PDO('mysql:host=localhost;dbname=mvcuser', 'root', '');
        $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    private function __clone(){}

    public static function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function query($sql) {
        return query($this->_db,$sql);
    }

}

And here is the code in my index.php file:

<?php
    require_once 'model/db.php';

    $db = Database::getInstance();

    $db->query('SELECT * FROM users');
    if ($result = $db->query($query)) {
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo $row;
    }
    }
  • 写回答

3条回答 默认 最新

  • douhao6557 2013-11-16 15:02
    关注

    The definition of your Database::query method doesn't make sense. It looks like you're calling some PHP function query (which doesn't exist) and thus you get the error.
    I think you might want to change the method's definition to:

    public function query($sql) {
        return $this->_db->query($sql);
    }
    

    Update: and in your index.php

    $db = Database::getInstance();
    $statement = 'SELECT * FROM users';
    
    if ($result = $db->query($statement)) {
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            echo $row;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮