I’m new to OOP and am trying to write my first app ?
I’ve created a class which uses the PDO to establish a connection to MySQL which itself works fine:
[CODE]
class DB {
const DBHOST = ‘localhost’;
const DBNAME = ‘xxxx’;
const DBUSER = ‘root’;
const DBPASS = ‘xxxx’;
function __construct(){
try {
$pdo = new PDO(“mysql:host=”.DB::DBHOST.”;dbname=”.DB::DBNAME, DB::DBUSER, DB::DBPASS);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $pdo;
}
}
but i now want to create another class (Property) which handles queries on the database such as INSERT, UPDATE, SELECT also using the PDO built in methods. I’m trying to make the Property class extend(?) the DB class so that only the Property class needs to be called in the client code. However, i’m having difficulty passing the PDO created in the DB class to it.
All i get is: [B]Fatal error: Call to undefined method DB:: prepare() in /home/…/class_lib.php on line 54
prepare() is method of the PDO object and it works fine if i instantiate another PDO object in my Property class, but that defeats the object of aiming towards reusable code does it not?!
This is the class where the error originates…
[CODE]
class Property{
private $dbh;
function __construct(){
$dbh = new DB();
$this->dbh = $dbh;
}
public function insertRow ($table,$field,$value){
$query = “INSERT INTO $table ($field) VALUES (?)”;
try {
$stmt = $this->dbh->prepare($query);
}
catch(PDOException $e) //IMPORTANT catch exception
{
echo $e->getMessage();
}
}
}
and the client code…
[CODE]
$dbh= new Property();
$dbh->insertRow(‘property_details’,’pty_desc’,’whatever’);
I’ve cut a bit of code out for sake of clarity but it irrelevant to the error.
Am i going about this in entirely the wrong fashion?!