与PDO和Singleton类的数据库连接 [英] Database connection with PDO and Singleton class

查看:48
本文介绍了与PDO和Singleton类的数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试与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.

我一直在阅读,但是我仍然不确定如何从另一个文件中调用数据库文件中的Singelton类,并打印出结果. 我现在得到的错误是db.php文件中的Fatal error: Call to undefined function query(),这是数据库文件中的最后一个函数.但是我相信该函数已定义.

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.

感谢您的帮助!

这是我的数据库(db.php)连接文件:

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

}

这是我的index.php文件中的代码:

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

推荐答案

Database::query方法的定义没有意义.看来您正在调用某些PHP函数query(该函数不存在),因此您会收到错误消息.
我认为您可能希望将方法的定义更改为:

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

更新:并且在您的index.php

$db = Database::getInstance();
$statement = 'SELECT * FROM users';

if ($result = $db->query($statement)) {
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo $row;
    }
}

这篇关于与PDO和Singleton类的数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆