Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem connecting with PDO

Tags:

php

mysql

pdo

It's the first time i'm using PDO just for testing purpose. But a strange error occurred and googling it, it seems to be weird.

Here's my database testing class

class db extends PDO
{
    # Our instance.
    private static $db = NULL;

    # Calling the connector.
    public static function connect()
    {
        if (self::$db === NULL)
        {
            $class = __CLASS__;
            self::$db = new $class();
        }
        return self::$db;
    }

    # Connector.
    public function __construct() 
    { 
        $dns = 'mysql:dbname='.reg::get('db-name').';host='.reg::get('db-host');
        self::$db = new PDO($dns, reg::get('db-username'), reg::get('db-password'));
        reg::delete('db-password');
    }

    # Quick reporting
    public function reportError($array)
    {
        if ($this->db != NULL) { echo 'Myself getting horny'; } // Just for testing, i'm not getting horny because of a mysql database connection!
    }

}

Then executing the following code:

$db = new db();
$row = $db->prepare('SELECT * FROM test WHERE id = :id')->execute(array('id' => 1));
echo $row['value'];

It shows me the following error:

Warning: PDO::prepare() [pdo.prepare]: SQLSTATE[00000]: No error: PDO constructor was not called in myfile.php on line 39

Considering line 39 as

$row = $db->prepare('SELECT * FROM test WHERE id = :id')->execute(array('id' => 1));
like image 311
Shoe Avatar asked Jan 21 '23 17:01

Shoe


1 Answers

You code is a mess, it's probably because you're so horny...

connect() method - why is it there?:

if ($db === NULL)

should be:

if (self::$db === NULL)

self::$db = new $class();

So, if $class == __CLASS__ == db, you are doing self::$db = new db();, doesn't seem right.


You can't use PDO to prepare an identifier, like a table or a column.

$db->prepare('SELECT * FROM :table WHERE id = :id')->execute(array('table' => 'test', 'id' => 1));

Should be:

$db->prepare('SELECT * FROM `test` WHERE id = :id')->execute(array('id' => 1));

Try this:

class db extends PDO
{
    private static $db = null;

    public static function singleton()
    {
        if (is_null(self::$db) === true)
        {
            self::$db = new PDO('mysql:dbname='.reg::get('db-name').';host='.reg::get('db-host'), reg::get('db-username'), reg::get('db-password'));
        }

        return self::$db;
    }
}

Like this:

$result = db::singleton()->prepare('SELECT * FROM `test` WHERE id = :id')->execute(array('id' => 1));

var_dump($result);
like image 188
Alix Axel Avatar answered Feb 01 '23 07:02

Alix Axel