Reputation: 54074
I am learning OOPS concept and also using PDO
, but really stuck in very basic problem, please look into my code and tell me what i am doing wrong and how to optimize this code.
###class.db.php
class DB
{
public $dbh;
private $qry;
public function __construct($user ='root',$pass = '')
{
try {
$this->dbh = new PDO('mysql:host=localhost;dbname=parixan',$user,$pass);
$this->dbh->exec("SET CHARACTER SET utf8");
echo "connected";
} catch(Exception $e){
die("Unable to connect: " . $e->getMessage());
}
}
}
###class.user.php
class User
{
public $db;
protected $_table ='tbl_user';
public function __construct($dbh)
{
$this->db = $dbh;
}
public function getUserDetails($id) //line #10
{
$qry = "SELECT * FROM $this->_table WHERE id = :userID LIMIT 1";
$stmt = $this->db->prepare($qry); //line #13
$stmt->bindParam(':userID',$id,PDO::PARAM_INT);
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<pre>";print_r($row);
}
}
}
}
###user.php
include_once('class.user.php');
include_once('class.db.php');
$dbh = new DB();
$obj_user = new User($dbh);
$obj_user ->getUserDetails(1);
on running user.php
I got this one
connected Fatal error: Call to undefined method DB::prepare() in C:\xampp\htdocs\oops\class.user.php on line 13
Thanks.
Upvotes: 1
Views: 182
Reputation: 238075
Within the User
object, $this->db
is a reference to an object of the DB
class. This class does not implement a prepare
method, so there is none available when you attempt to call it with $stmt = $this->db->prepare($qry);
.
If you persist with your current class design, you need to create such a function:
public function prepare($qry) {
return $this->dbh->prepare($qry);
}
This means you will now have a PDOStatement
object, on which you can call bindParam
and execute
.
Upvotes: 2