我已在我的项目中为我的数据库连接编写了这个小类:
<?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);
}
}
?>
这就是我使用它的方式:
<?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");
?>
但我收到以下错误:
Could not find driver
我是PDO的新手,所以请指导我做错了什么?这种方法对于安全快速的数据库活动是否合适?
更新 我现在使用这些代码行来使用我的DatabaseUtility类,但是出现了错误:
<?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);
?>
错误是:
call to a member function bindParam() on a non-object in this line:
$statment->bindParam("img_id", $id ,PDO::PARAM_INT);
答案 0 :(得分:2)
您似乎没有在prepareStatment()
方法中返回任何内容。
public function prepareStatment($query){
return $this->pdo->prepare($query);
}
这是$statment = $db->prepareStatment("Select offer_id from offer_images where img_id = :img_id");
返回false的原因。