如何将 mysql_connect() 更改为 PDO

how to change mysql_connect() to PDO

这是我的数据库连接 class,它正在与 php5.3 一起工作,但在我更新 php5.4 后它不工作并显示它已过期的错误。

class DB {
   function DB() {
       $this->host = "localhost";
       $this->db = "dbtest";
       $this->user = "root" ;
       $this->pass = "password";
       $this->link = mysql_connect($this->host, $this->user, $this->pass) or die("<br>Could not connect 1: " . mysql_error());
       mysql_select_db($this->db);
   }
   function query($query) {
       $result = mysql_query($query, $this->link) or die ("<br>Could not execute command 1: ".mysql_error());
       return $result;
   }
   function thislink() {
       return $this->link;
   }
   function close() {
       mysql_close($this->link);
   }
}

如何将其更改为 PDO 或 mysqli 以便 wamp 可以使用它

class DB {
   function DB() {
       $this->host = "localhost";
       $this->db = "dbtest";
       $this->user = "root" ;
       $this->pass = "password";
       $this->link = new PDO("mysql:host=$this->host;dbname=$this->db", $this->user, $this->pass);
   }
   function query($query) {
       $result = $this->link->query($query);
       return $result;
   }
   function thislink() {
       return $this->link;
   }
   function close() {
       $this->link = NULL;
   }
}

您的 class 应如下所示:

请注意,我将构造函数更改为 __construct(),因为在 PHP 7 中,您使用的另一种方式将被弃用。此外,我将变量作为参数放入具有默认值的构造函数中。我还为您的 PDO 连接启用了 error mode,仅在测试中启用!从未在生产中启用。

<?php

    class DB {

        public $host;
        public $db;
        public $user;
        public $pass;

        private $link;

        public function __construct($host = "localhost", $db = "dbtest", $user = "root", $pass = "password") {
            $this->host = $host;
            $this->db = $db;
            $this->user = $user;
            $this->pass = $pass;

            try {
                $this->link = new PDO("mysql:host={$this->host};dbname={$this->db}", $this->user, $this->pass);
                $this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch(PDOExcpetion $e) {
                echo $e->getMessage();
            }

        }

        function query($query) {    
            $stmt = $this->link->prepare($query);
            $stmt->execute();
            return $stmt;
        }

        function thislink() {
            return $this->link;
        }

        function close() {
            $this->link = null;
        }

    }


?>

有关 PDO 的更多信息,请参阅手册:http://php.net/manual/en/book.pdo.php

您可能还想看看 prepared statements

你不能。

你的 class 不是黑盒子,你有一个 public 方法,returns MySQL link 标识符:

function thislink() {
   return $this->link;
}

如果您将其更改为另一个数据库接口,您将在调用此方法时 运行 遇到问题,因为它不包含调用端所期望的内容。

这同样适用于您的 public query() 方法:

function query($query) {
   $result = mysql_query($query, $this->link) or die ("<br>Could not execute command 1: ".mysql_error());
   return $result;
}

returns 一个 mysql 资源,例如 SELECT 语句,因此如果您将其更改为 msyqli 或 PDO,调用方将无法处理它.