Reputation: 1
I am trying to learn PHP OOP concept and has a database connection using PDO as below:
class db{
private $host;
private $user;
private $pass;
private $dname;
private $conn;
function __construct(){
$this->host = "localhost";
$this->user = "root";
$this->pass = "";
$this->dname= "nast";
$this->connect();
}
function __destruct(){
$this->disconnect();
}
function connect(){
if(!$this->conn){
try{
$this->conn = new PDO('mysql:host='.$this->host.'; dbname='.$this->dname.'', $this->user, $this->pass,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch(Exception $e){
die('Erreur:' .$e->getMessage());
}
if(!$this->conn){
$this->status_fatal = true;
echo'Connection Not Established';
die();
}
else{
$this->status_fatal = false; }
}
return $this->conn;
}
function disconnect(){
if($this->conn){
$this->conn = null;
}
}
}
And named it "class.db.php". I got it from internet.
Then I tried to retrieve data from the database using the following code
require 'class.db.php';
$bdd = new db(); // create a new object, class db()
$sql = 'SELECT * FROM student';
$q = $bdd->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$r = $q->fetch();
echo $r['id'];
But it give the following error:
Call to undefined method db::query() in C:\xampp\htdocs\prac\class.my.php on line 8.
Upvotes: 0
Views: 85
Reputation: 6625
As what the error
says, the function query()
doesn't exist in your db
class. Add a query function on your db
class, something like this:
function query($sql){
$this->connect(); // open a connection
// do your codes here
$this->disconnect(); // close the connection
}
Upvotes: 1