Hey guys, so I'm completely new to Object Oriented PHP -- I've read some tutorials, but I can't find anything that really goes into working with a database with PHP classes.
I'm trying to make something simple -- a quick news post class. You get the post from the database, etc. However, I'm getting an error whenever I try to interact with the database.
I read that PDO is the way to go with OO PHP; to that end, I've developed a database class, as detailed in this post: http://stackoverflow.com/questions/2047264/use-of-pdo-in-classes
class Database
{
public $db; // handle of the db connexion
private static $dsn = "mysql:host=localhost;dbname=test";
private static $user = "admin";
private static $pass = "root";
private static $instance;
public function __construct ()
{
$this->db = new PDO(self::$dsn,self::$user,self::$pass);
}
public static function getInstance()
{
if(!isset(self::$instance))
{
$object= __CLASS__;
self::$instance=new $object;
}
return self::$instance;
}
// others global functions
}
I then attempt to use it in my PHP class, in order to retrieve data on a news post:
<?php
require_once "database.php";
class news extends Database
{
private $title;
private $author;
private $date;
private $content;
private $category;
function __construct($id)
{
$db = Database::getInstance();
$query = $this->db->prepare("SELECT title, author, date, content, category FROM news WHERE id = :id LIMIT 1");
$query->bindParam(":id", $this->id, PDO::PARAM_INT);
if ($query->execute())
{
$result = $query->fetch(PDO::FETCH_OBJ);
$this->set_title($result->title);
$this->set_author($result->author);
$this->set_date($result->date);
$this->set_content($result->content);
$this->set_category($result->category);
}
}
<...>
?>
Every time I try to run this script though, I get the following error:
Fatal error: Call to a member function prepare() on a non-object in /news.class.php on line 16
Any ideas?