I'm newbie on PDO. I watch several videos. And i want to use my own database class as previous times. I want to use PDO instead of mysql* functions. I know that mysql* functions are deprecated in PHP 5.5
I am not working on my old database class. Because it'll be more harder for a newbie. Now i only create a connection. And i want to select my products.
Here is my code :
class Database extends PDO {
private $_server = "localhost";
private $_user = "root";
private $_password = "";
private $_db = "demo";
private $_engine = 'mysql';
private $link = NULL;
public function __construct() {
$dsn = $this->_engine.':dbname='.$this->_db.';host='.$this->_server.';charset=utf8';
try {
$this->link = new PDO($dsn, $this->_user, $this->_password);
$this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
header('Content-Type: text/html; charset=utf-8');
$DB = new Database();
$sql = "SELECT * FROM product";
$q = $DB->query($sql);
while($r = $q->fetch(Database::FETCH_ASSOC)){
$products[] = $r;
}
echo "<pre>";
print_r($products);
echo "</pre>";
I couldn't fetch my products. I'm recieving errors.
Warning: PDO::query(): SQLSTATE[00000]: No error: PDO constructor was not called in /var/www/dt/includes/class/class.database.php on line 52
Fatal error: Call to a member function fetch() on a non-object in /var/www/dt/includes/class/class.database.php on line 53
What is my mistake ? And what should i do ?