我为我的项目编写了这个小类来处理数据库连接:
<?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);