Johnny
Johnny

Reputation: 11

PDO class not working - call to member function prepare

I have a question regarding my PDO class. It's not working and creates this error: "Notice: Undefined variable: db in classes.php on line 21 Fatal error: Call to a member function prepare() on a non-object in classes.php on line 32. I tried to fix this code for several hours but i don't find the error. Your help would be appreciated!

Thank you in advance.

<?
// classes.php

class Connection{

    public static $db;

    function __construct() 
    {
        try {
            $this->$db = new PDO('mysql:host=localhost;dbname=vnm', '--', '--', array(PDO::ATTR_PERSISTENT => true));
            $this->$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }   
    }

    public function GetAccess()
    {
        return $db;
    }

}

class Page
{
    public function show_page($s_p1)
    {
         $db = Connection::GetAccess();
         $id = "1";
         $stmt = $db->prepare('SELECT * FROM users WHERE id = :id');
         $stmt->execute();
         while($row = $stmt->fetch())
         {
             print_r($row);
         }
    }
}?>

Upvotes: 1

Views: 234

Answers (2)

Namal
Namal

Reputation: 2071

try this. I removed all static methods.

    <?
// classes.php

class Connection{

    public $db;

    function __construct() 
    {
        try {
            $this->$db = new PDO('mysql:host=localhost;dbname=vnm', '--', '--', array(PDO::ATTR_PERSISTENT => true));
            $this->$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }   
    }

    public function GetAccess()
    {
        return $this->$db;
    }

}

class Page
{
    public function show_page($s_p1)
    {
         $con = new Connection();
         $db = $con->GetAccess();
         $id = "1";
         $stmt = $db->prepare('SELECT * FROM users WHERE id = :id');
         $stmt->execute();
         while($row = $stmt->fetch())
         {
             print_r($row);
         }
    }
}?>

Upvotes: 0

kitti
kitti

Reputation: 14834

Static members must be accessed using static::. You directly access $db in your code, and incorrectly use $this->db, when you should be using static::$db. You also need to declare GetAccess as a public static function.

Also, calling Connection::GetAccess doesn't actually instantiate the class, so static::$db will probably be null, unless you create your singleton instance elsewhere.

You can read more about singletons here: http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html

Upvotes: 2

Related Questions