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.
Within the
Userobject,$this->dbis a reference to an object of theDBclass. This class does not implement apreparemethod, 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:
This means you will now have a
PDOStatementobject, on which you can callbindParamandexecute.