Connecting to a database with PDO and Singleton class

I am trying to establish a database connection with PDO and Singleton class, but you have problems getting data from the database.

I read about this, but I still donโ€™t know what to call the Singelton class in my database file from another file and get a printout of the results. The error I'm getting right now is a fatal error: a call to the undefined function query () in my db.php file. Last function in my database file. However, I believe the function is defined?

Any help appreciated!

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

<?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;
    }
    }
+4
source share
2 answers

Database::query . , PHP query ( ), .
, :

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

, , , Google, PDO, .

public function __call ( $method, $args ) {
    if ( is_callable(array($this->_db, $method)) ) {
        return call_user_func_array(array($this->_db, $method), $args);
    }
    else {
        throw new BadMethodCallException('Undefined method Database::' . $method);
    }
}

$db->query($statement) PDO .

+6

All Articles