在PHP中使用PDO连接数据库

4

我为我的项目编写了这个小类来处理数据库连接:

 <?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);

看起来您的服务器上没有安装 PHP PDO 模块。 - Aleksandar Vasić
你的服务器的php.ini文件中是否启用了PDO驱动程序? - Jay Blanchard
我正在本地主机上使用它,就我所知,它已在PHP.ini文件中启用。 - Subhan
2个回答

3
所以看起来你正在将 MYSQL 作为数据库与 PHP 中的 MYSQL API 混合使用,例如 PDO, mysqli_*mysql_*
您使用 PDO 作为 API 连接到 MYSQL 数据库。但是您的 连接 字符串中有一些小错误:
                        //vvvvv < -- > vvvvvvvvv
$this->dsn = "mysqli:host=$host;dbname:$database";
                 //^ ^^^^ < - > ^^^^^^^ must be a equal sign
                 //| Your database is MYSQL so remove the i

很好的=捕捉。 - cmorrissey
不将 prepare 分配给变量或返回它怎么样 $stmt = $this->pdo->prepare($query); - cmorrissey
抱歉,我没有明白你的意思。 - Subhan
请现在回答我的问题,因为我提到了一个新的问题。 - Subhan
@SubhanAhmed 还要将您的预备语句放在 try 和 catch 块中,看看是否会出现任何错误。 - Rizier123
显示剩余2条评论

2

看起来你的prepareStatement()方法没有返回任何内容。

public function prepareStatment($query){
    return $this->pdo->prepare($query);
}

造成$statment = $db->prepareStatment("Select offer_id from offer_images where img_id = :img_id");返回false的原因是什么。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接