jerrygarciuh
jerrygarciuh

Reputation: 21998

PHP define() and PDO connection string issues

I made a small test script while trying to solve issues with sessions going missing after switching to PDO.

In testing the script I am finding that every other load of the page gets

Access denied for user 'DB_USER'@'[ip snipped]' (using password: YES)

So DB_USER is uninterpolated for every second load. The first load of the page gets a successful connection.

Why is that? PHP version is 5.4.42.

<?
session_start();
define("DB_HOST", "myserver");
define("DB_USER", "myuser");
define("DB_PASS", "mypass");
define("DB_NAME", "mydb");


class DB {  
    protected $link;

    public function __construct() {
        $this->dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';
        $this->connect();
    }

    private function connect() {
        $options = array(
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );
        $this->pdo = new PDO($this->dsn, DB_USER, DB_PASS, $options);
    }

    public function __sleep() {
        return array('dsn', 'username', 'password');
    }

    public function __wakeup() {
        $this->connect();
    }
}

$db = new DB;

Upvotes: 0

Views: 143

Answers (1)

ob_start
ob_start

Reputation: 276

public function __wakeup() {
    $this->dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';
    $this->connect();
}

will fix this. But the main problem is that you havent define variables like

protected $dsn;

So the wakup fails.

Upvotes: 1

Related Questions