与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.

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

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

I know this questing is a little old, but for anyone who found it from Google if you don’t want to create a wrapper method for every single PDO method, you can use this inside your singleton class.

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

Now you can use $db->query($statement) or any other PDO method without having to define it inside your singleton class.

Just thought about this question. I make different way to connect database. Also it's included form. it's like this.

PHP

class try_connect
{
    function connect($s_name,$db_name,$user,$pass)
    {
        $this->s_name = $s_name;
        $this->db_name = $db_name;
        $this->user = $user;
        $this->pass = $pass;
        try {
            $db = new PDO("mysql:host=$s_name;dbname=$db_name","$user","$pass");
            if ($db) {
                echo $db->query("select database()")->fetch(PDO::FETCH_COLUMN);
            }else {
                echo "fail";
            }
        } catch (Exception $e) {
            print $e->getMessage();
        }
    }
}
if (isset($_POST["submit"])) {
    $get_server_name = $_POST["server_name"];
    $get_db_name = $_POST["database_name"];
    $get_user = $_POST["user"];
    $get_pass = $_POST["password"];
    $connect = new try_connect();
    $connect->connect($get_server_name,$get_db_name,$get_user,$get_pass);
}

HTML

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
    <p><input type="text" name="server_name"></p>
    <p><input type="text" name="database_name"></p>
    <p><input type="text" name="user"></p>
    <p><input type="text" name="password"></p>
    <p><input type="submit" name="submit"></p>
</form>

Coding really nice. I love it. :)