Question

Below is the db connection class, but I am going to improve it by extending the PDO class itself:

<?php

class db{


private static $instance = NULL;

public function __construct() {
}

public static function getInstance() {

if (!self::$instance)
{
self::$instance = new PDO("mysql:host=localhost;dbname=dbmvc", 'root', '');;
self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}


private function __clone(){
}

}

?>

extended class:

<?php 

class Model extends db{


final public function fetchInfo() 
{

global $pdo, $db;

$query = $db->prepare("SELECT name FROM table");
$query->execute();

$result = $query -> fetchAll();

foreach( $result as $row ) 
{
echo $row['name'];
}

}
}

?>

But I have errors when I call this method:

 $model=new Model();
 $model->fetchInfo();

error is:

Call to a member function prepare() on a non-object in C:\xampp\htdocs\mvc\model\model.class.php on line 11

I am new to PDO, and I trying to figure it out but I can't find solution anywhere, can anyone help. Tnx!

Was it helpful?

Solution

This issue has nothing to do with PDO per se, but with object-oriented programming.

  • You declare global $db which you should be using self::$db or else making a distinct instance variable.

  • You didn't initialize $db before you called a method on it. You should set it to self::getInstance().

  • You declare a reference to a variable global $pdo which you never define and never use. This is just sloppy coding.

  • A model is not a database instance. You should prefer composition over inheritance in this case.

OTHER TIPS

If you would like to see a very nice example of objects such as these I recommend reviewing this Database Class from the PHP-Login script by panique on GitHub. As well as this Model class from the same set of scripts. I hope this helps :D

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top