Reputation: 1634
I've written this small class for my database connections in my project:
<?php
class DatabaseUtility{
private $dsn, $username, $password, $database, $pdo;
public function __construct($host = 'localhost', $username = 'root', $password = '', $database){
$this->dsn = "mysqli:dbname=$database;host:$host";
$this->username = $username;
$this->password = $password;
$this->database = $database;
}
public function connect(){
try{
$this->pdo = new PDO($this->dsn,$this->username,$this->password,null);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $err){
die($err->getMessage());
}
}
public function prepareStatment($query){
$this->pdo->prepare($query);
}
}
?>
And this is how i'm using it:
<?php
require 'DatabaseUtility.php';
$db = new DatabaseUtility('localhost','root','','apex');
$db->connect();
$statment = $db->prepareStatment("Select offer_id from offer_images where img_id = :img_id");
?>
But i'm getting the following error:
Could not find driver
I'm new to PDO stuff so please do guide me what i'm doing wrong? Is this method okay for a secure and fast database activity?
Update: I'm now using these lines of code to use my DatabaseUtility class but got an error:
<?php
require 'DatabaseUtility.php';
$id= 25;
$db = new DatabaseUtility('localhost','root','','apex');
$db->connect();
$statment = $db->prepareStatment("Select offer_id from offer_images where img_id = :img_id");
$statment->bindParam("img_id", $id ,PDO::PARAM_INT);
$statment->execute();
print_r($statment);
?>
Error is:
call to a member function bindParam() on a non-object in this line:
$statment->bindParam("img_id", $id ,PDO::PARAM_INT);
Upvotes: 4
Views: 1915
Reputation: 238
It looks like you are not returning anything in your prepareStatment()
method.
public function prepareStatment($query){
return $this->pdo->prepare($query);
}
This is the reason $statment = $db->prepareStatment("Select offer_id from offer_images where img_id = :img_id");
was returning false.
Upvotes: 2
Reputation: 59701
So it seems like you're mixing MYSQL
as database with the MYSQL API's in PHP e.g. PDO
, mysqli_*
or mysql_*
.
You use PDO
as API to connect to your MYSQL database. But you have a few little errors in your connection string:
//vvvvv < -- > vvvvvvvvv
$this->dsn = "mysqli:host=$host;dbname:$database";
//^ ^^^^ < - > ^^^^^^^ must be a equal sign
//| Your database is MYSQL so remove the i
Upvotes: 3