Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP Class Database interaction (using PDO)
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <p>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: <a href="https://stackoverflow.com/questions/2047264/use-of-pdo-in-classes">Use of PDO in classes</a></p> <pre><code>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-&gt;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 } </code></pre> <p>I then attempt to use it in my PHP class, in order to retrieve data on a news post:</p> <pre><code>&lt;?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-&gt;db-&gt;prepare("SELECT title, author, date, content, category FROM news WHERE id = :id LIMIT 1"); $query-&gt;bindParam(":id", $this-&gt;id, PDO::PARAM_INT); if ($query-&gt;execute()) { $result = $query-&gt;fetch(PDO::FETCH_OBJ); $this-&gt;set_title($result-&gt;title); $this-&gt;set_author($result-&gt;author); $this-&gt;set_date($result-&gt;date); $this-&gt;set_content($result-&gt;content); $this-&gt;set_category($result-&gt;category); } } &lt;...&gt; ?&gt; </code></pre> <p>Every time I try to run this script though, I get the following error:</p> <p>Fatal error: Call to a member function prepare() on a non-object in /news.class.php on line 16</p> <p>Any ideas?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload