問題描述
在 php.net 上閱讀有關 MySQL 函數的內容時.我遇到了這個消息
<塊引用>警告這個擴展從 PHP 5.5.0 開始被棄用,將來會被刪除.相反,應使用 MySQLi 或 PDO_MySQL 擴展.另請參閱 MySQL:選擇 API 指南和相關常見問題以了解更多信息.此函數的替代方法包括:
- mysqli_connect()
- PDO::__construct()
我讀過有關 PDO 的文章.如何使用 MySQL 或 MSSQL 將我的代碼更新為 PDO?
我看到很多關于實現my_sql 函數的代碼.其他人(包括我自己)的評論迫使提問者放棄MySQL 函數并開始使用 PDO 或 MySQLI.這篇文章是來幫忙的.您可以參考它,因為它解釋了為什么不推薦使用它們以及 PDO 是什么,以及實現 PDO 的最小代碼示例.
首先:
從mysql 函數 到PDO 的轉換不是一個簡單的搜索和替換案例.PDO 是 PHP 語言的面向對象編程插件.這意味著使用 mysql 函數 編寫代碼的另一種方法.首先為什么要轉換?
為什么不推薦使用 mysql 函數?
<塊引用>mysql 擴展很古老,從 15 年前發布的 PHP 2.0 開始就已經存在(!!);這與試圖擺脫過去不良做法的現代 PHP 截然不同.mysql 擴展是一個非常原始的、低級的 MySQL 連接器,它缺乏許多方便的特性,因此很難以安全的方式正確應用;因此,這對菜鳥不利.許多開發人員不了解 SQL 注入,而且 mysql API 非常脆弱,即使您知道它也很難阻止它.它充滿了全局狀態(例如隱式連接傳遞),這使得編寫難以維護的代碼變得容易.由于它很舊,在 PHP 核心級別維護可能會非常困難.
mysqli 擴展更新了很多,并修復了上述所有問題.PDO 也是相當新的,也解決了所有這些問題,以及更多.
由于這些原因* mysql 擴展將在未來某個時候被刪除.
source Deceze
如何實施 PDO
PDO 提供了一種連接多個數據庫的解決方案.此答案僅涵蓋 MySQL 和 MSSQL 服務器.
連接到 MySQL 數據庫,先決條件
這相當簡單,不需要任何 PHP 預先設置.現代 PHP 安裝標配一個模塊,該模塊允許 PDO 連接到 MySQL 服務器.
<塊引用>模塊為php_pdo_mysql.dll
連接到 MSSQL 數據庫,先決條件
這是一個更高級的設置.您需要 php_pdo_sqlsrv_##_ts.dll
或 php_pdo_sqlsrv_##_nts.dll 驅動程序
.它們是特定于版本的,因此是 ##
.在撰寫本文時,Microsoft 已發布PHP 5.5.x 的官方驅動程序.5.6 驅動程序尚未由 Microsoft 正式發布,但可以通過 其他.
模塊是 php_pdo_sqlsrv_##_ts.dll
用于線程安全變體該模塊是 php_pdo_sqlsrv_##_nts.dll
用于非線程安全變體
使用 PDO 連接到數據庫要連接到數據庫,您需要從 PDO 構造創建一個新的 PDO 實例.
$connection = new PDO(arguments);
PDO 構造函數采用 1 個必需參數和 3 個可選參數.
- DSN 或數據源名稱,主要是一個字符串,包含有關驅動程序、主機和數據庫名稱的信息.自 PHP 7.4 起,它還可以包含用戶名和密碼.
- 用戶名
- 密碼
- 選項
連接到MySQL
$dsn = 'mysql:dbname=databasename;host=127.0.0.1';$user = 'dbuser';$password = 'dbpass';$dbh = new PDO($dsn, $user, $password);
我們來看看$dsn
:首先它定義了驅動程序(mysql
).然后是數據庫名稱,最后是主機.
連接到 MSSQL
$dsn = 'sqlsrv:Server=127.0.0.1;Database=databasename';$user = 'dbuser';$password = 'dbpass';$dbh = new PDO($dsn, $user, $password);
我們來看看$dsn
:首先它定義了驅動程序(sqlsrv
).然后是主機,最后是數據庫名稱.
當您創建實例時,會建立與數據庫的連接.在執行 PHP 腳本期間,您只需執行一次此操作.
<塊引用>您需要將 PDO 實例創建包裝在 try-catch 子句中.如果創建失敗,則會顯示一個回溯,其中會顯示有關您的應用程序的關鍵信息,例如用戶名和密碼.為避免這種情況,捕獲錯誤.
試試{$connection = new PDO($dsn, $user, $password);}catch( PDOException $Exception ){echo "無法連接數據庫.";出口;}
<塊引用>
要拋出 SQL 服務器返回的錯誤,請使用 setAttribute
將此選項添加到 PDO 實例:$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );代碼>
執行查詢
PDO 使用準備好的語句.這是PDO 方法和mysql 函數 之間的真正區別.后者很容易受到SQL-INJECTION 的影響.一個人會像這樣構建一個查詢:
$SQL = 'SELECT ID FROM users WHERE user = '.$username ;
當惡意網站或個人發布用戶名時注入器;刪除表用戶
.結果將是毀滅性的.您需要通過使用引號轉義和封裝字符串和變量來證明您的代碼.這不得不做對于每個查詢.在較大的網站或維護不善的代碼上,擁有允許 SQL 注入的表單的風險可能會變得非常高.準備好的語句消除了第一層 SQL 注入的機會,就像上面的例子一樣.
PDO 驅動程序充當 PHP 服務器和數據庫服務器之間的中間人,稱為數據訪問抽象層.它不會重寫您的 SQL 查詢,但確實提供了一種連接到多種數據庫類型的通用方法并為您處理將變量插入到查詢中.Mysql 函數 構建了對 PHP 代碼執行的查詢.使用 PDO,查詢實際上是在數據庫服務器上構建的.
準備好的 SQL 示例:
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
注意區別;PHP 變量不是在字符串外使用 $
,而是在字符串內使用 :
引入變量.另一種方式是:
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = ?';
如何執行實際查詢
您的 PDO 實例提供了兩種執行查詢的方法.當您沒有變量時,您可以使用 query()
,變量使用 prepare()
.query()
在調用時立即執行.請注意調用的面向對象方式(->
).
$result = $connection->query($SQL);
準備方法
prepare 方法 接受兩個參數.第一個是 SQL 字符串,第二個是數組形式的選項.一個基本的例子
$connection->prepare($SQL, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
在我們的 SQL 字符串示例中,我們使用了一個名為 :username
的命名變量.我們仍然需要將一個 PHP 變量、整數或字符串綁定到它.我們可以通過兩種方式做到這一點.要么構建一個包含命名變量作為 key
的數組,要么使用 bindParam
或 bindValue
方法.為簡單起見,我將解釋數組變量和方法 bindValue
.
數組
你可以對命名變量做這樣的事情,你提供變量作為數組鍵:
$queryArguments = array(':username' => $username);
這對于索引變量(?
):
$queryArguments = array($username);
當您添加了所有需要的變量后,您可以調用方法 execute()
來執行查詢.從而將數組作為參數傳遞給函數 execute
.
$result = $connection->execute($queryArguments);
bindValue
bindValue 方法允許您將值綁定到 PDO 實例.該方法采用兩個必需參數和一個可選參數.可選參數設置值的數據類型.
對于命名變量:
$connection->bindValue(':username', $username);
對于索引變量:
$connection->bindValue(1, $username);
將值綁定到實例后,您可以調用 execute
而無需傳遞任何參數.
$result = $connection->execute();
<塊引用>
注意:一個命名變量只能使用一次!使用它們兩次將導致執行查詢失敗.根據您的設置,這會或不會引發錯誤.
獲取結果
同樣,我將只介紹從返回的集合中獲取結果的基礎知識.PDO 是一個相當先進的附加組件.
使用 fetch
和 fetchAll
如果您執行了選擇查詢或執行了返回結果集的存儲過程:
獲取
fetch
是一種最多可以使用三個可選參數的方法.它從結果集中獲取一行.默認情況下,它返回一個 array ,其中包含列名作為鍵和索引結果.我們的示例查詢可能會返回類似
ID EMAIL1 人@example.com
fetch
將返回:
數組([ID] =>1[0] =>1[電子郵件] =>有人@example.com[1] =>有人@example.com)
要回顯結果集的所有輸出:
while($row = $result->fetch()){回聲 $row['ID'];回聲 $row['EMAIL'];}
您可以在此處找到其他選項:fetch_style;>
fetchAll
獲取單個數組中的所有行.使用與 fetch
相同的默認選項.
$rows = $result->fetchAll();
如果您使用的查詢不返回結果,例如插入或更新查詢,您可以使用方法 rowCount
來檢索受影響的行數.
一個簡單的類:
class pdoConnection {公共 $isConnected;受保護的 $connection;公共函數 __construct($dsn, $username, $password, $options = array()) {$this->isConnected = true;嘗試 {$this->connection = new PDO($dsn, $username, $password, $options);$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);$this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);//設置默認返回數組中的命名"屬性.} catch (PDOException $e) {$this->isConnected = false;拋出新異常($e->getMessage());}}公共函數斷開(){$this->connection = null;$this->isConnected = false;}公共函數查詢($SQL){嘗試 {$result = $this->connection->query($SQL);返回 $result;} catch (PDOException $e) {throw new PDOException($e->getMessage());}}公共函數準備($SQL,$params = array()){嘗試 {$result = $this->connection->prepare($SQL);$result->execute($params);返回 $result;} catch (PDOException $e) {throw new PDOException($e->getMessage());}}}
使用方法:
$dsn = 'mysql:dbname=databasename;host=127.0.0.1';$user = 'dbuser';$password = 'dbpass';$db = new pdoConnection($dsn, $user, $password);$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';$result = $db->prepare($SQL, array(":username" => 'someone'));while($row = $result->fetch()){回聲 $row['ID'];回聲 $row['EMAIL'];}
When reading on php.net about MySQL functions. I encountered this message
Warning This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
- mysqli_connect()
- PDO::__construct()
I've read about PDO. How can I update my code to PDO using either MySQL or MSSQL?
I see a lot of code posted on SO implementing my_sql functions. And comments from others (including myself) pressing the questioners to abandon MySQL functions and start using PDO or MySQLI. This post is here to help. You can refer to it as it provides explanation to why they are deprecated and what PDO is, plus a minimal code example to implement PDO.
First of all:
Conversion from mysql functions to PDO is not a simple case of search and replace. PDO is an Object Oriented Programming add on for the PHP language. That means an other approach in writing the code as with the mysql functions. First why convert?
Why are mysql functions deprecated?
The mysql extension is ancient and has been around since PHP 2.0, released 15 years ago (!!); which is a decidedly different beast than the modern PHP which tries to shed the bad practices of its past. The mysql extension is a very raw, low-level connector to MySQL which lacks many convenience features and is thereby hard to apply correctly in a secure fashion; it's therefore bad for noobs. Many developers do not understand SQL injection and the mysql API is fragile enough to make it hard to prevent it, even if you're aware of it. It is full of global state (implicit connection passing for instance), which makes it easy to write code that is hard to maintain. Since it's old, it may be unreasonably hard to maintain at the PHP core level.
The mysqli extension is a lot newer and fixes all the above problems. PDO is also rather new and fixes all those problems too, plus more.
Due to these reasons* the mysql extension will be removed sometime in the future.
source Deceze
How to implement PDO
PDO offers one solution for connecting to multiple databases. This answer covers only MySQL and MSSQL servers.
Connecting to a MySQL database, prerequisites
This is fairly simple and doesn't require any pre set-up of PHP. Modern PHP installations are standard shipped with a module that allows PDO connections to MySQL servers.
The module is
php_pdo_mysql.dll
Connecting to a MSSQL database, prerequisites
This is a more advanced set-up. You need php_pdo_sqlsrv_##_ts.dll
or php_pdo_sqlsrv_##_nts.dll drivers
. They are version specific hence the ##
. At the moment of writing, Microsoft has released
official drivers for PHP 5.5.x. The 5.6 drivers aren't yet officially released by Microsoft, but are available as non-official builds by others.
The module is
php_pdo_sqlsrv_##_ts.dll
for the thread safe variant The module isphp_pdo_sqlsrv_##_nts.dll
for the non-thread safe variant
Connecting to a database using PDO To connect to a database you need to create a new PDO instance from the PDO construct.
$connection = new PDO(arguments);
The PDO constructor takes 1 required arguments and 3 optional.
- DSN or Data Source Name, mostly this is a string containing information about the driver, host and database name. Since PHP 7.4 it can also include username and password.
- Username
- Password
- Options
Connecting to MySQL
$dsn = 'mysql:dbname=databasename;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
Let's take a look at $dsn
: First it defines the driver (mysql
). Then the database name and finally the host.
Connecting to MSSQL
$dsn = 'sqlsrv:Server=127.0.0.1;Database=databasename';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
Let's take a look at $dsn
: First it defines the driver (sqlsrv
). Then the host and finally the database name.
When you create the instance a connection is made to the database. You only have to do this once during the execution of a PHP script.
You need to wrap the PDO instance creation in a try-catch clause. If the creation fails a back trace is shown revealing critical information about your application, like username and password. To avoid this catch the errors.
try
{
$connection = new PDO($dsn, $user, $password);
}
catch( PDOException $Exception )
{
echo "Unable to connect to database.";
exit;
}
To throw errors returned by your SQL server add this options to your PDO instance using
setAttribute
:$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Performing queries
PDO uses prepared statements. This is a real difference between PDO's approach and mysql functions. The latter was very susceptible to SQL-INJECTION. One would build a query like this:
$SQL = 'SELECT ID FROM users WHERE user = '.$username ;
When a malicious website or person posts the username injector; DROP TABLE users
. The results will be devastating. You needed to proof your code by escaping and encapsulating strings and variables with quotes. This had to be done
for every query. On larger websites or poorly maintained code the risk of having a form that allowed SQL injection could become very high. Prepared statements eliminates the chance of first tier SQL injection like the example above.
The PDO drivers act as a man-in-the-middle between your PHP-server and database server, called a data-access abstraction layer. It doesn't rewrite your SQL queries, but do offer a generic way to connect to multiple database types and handles the insertion of variables into the query for you. Mysql functions constructed the query on execution of the PHP code. With PDO the query actually gets build on the database server.
A prepared SQL example:
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
Note the difference; Instead of a PHP variable using $
outside the string, we introduce a variable using :
within the string. Another way is:
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = ?';
How to perform the actual query
Your PDO instance provides two methods of executing a query. When you have no variables you can use query()
, with variables use prepare()
. query()
is immediately executed upon calling. Please note the object oriented way of the call (->
).
$result = $connection->query($SQL);
The prepare method
The prepare method takes two arguments. The first is the SQL string and the second are options in the form of an Array. A basic example
$connection->prepare($SQL, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
In our SQL string example we've used a named variable called :username
. We still need to bind a PHP variable, integer or string to it. We can do this in two ways. Either build an array containing the named variables as key
or use the method bindParam
or bindValue
.
I will explain the array variant and the method bindValue
for the sake of simplicity.
Array
You can do something like this for named variables, where you provide the variable as array key:
$queryArguments = array(':username' => $username);
And this for indexed variables (?
):
$queryArguments = array($username);
When you have added all the variables you need you can call upon the method execute()
to perform the query. Thereby passing the array as argument to the function execute
.
$result = $connection->execute($queryArguments);
bindValue
The bindValue method allows you to bind values to the PDO instance. The method takes two required arguments and one optional. The optional arguments set the data-type of the value.
For named variables:
$connection->bindValue(':username', $username);
For indexed variables:
$connection->bindValue(1, $username);
After binding the values to the instance, you can call upon execute
without passing any arguments.
$result = $connection->execute();
NOTE: You can only use a named variable once! Using them twice will result in a failure to execute the query. Depending on your settings this will or will not throw an error.
Fetching the results
Again I will only cover the basics for fetching results from the returned set. PDO is a fairly advanced add-on.
Using fetch
and fetchAll
If you did a select query or executed a stored procedure that returned a result set:
fetch
fetch
is a method that could take up to three optional arguments. It fetches a single row from the result set. By default it returns an array containing the column names as keys and indexed results.
Our example query could return something like
ID EMAIL
1 someone@example.com
fetch
will return this as:
Array
(
[ID] => 1
[0] => 1
[EMAIL] => someone@example.com
[1] => someone@example.com
)
To echo all output of a result set:
while($row = $result->fetch())
{
echo $row['ID'];
echo $row['EMAIL'];
}
There are other options you can find here: fetch_style;
fetchAll
Fetches all rows in a single array. Using the same default option as fetch
.
$rows = $result->fetchAll();
If you used a query that didn't return results like a insert or update query you can use the method rowCount
to retrieve the amount of rows affected.
A simple class:
class pdoConnection {
public $isConnected;
protected $connection;
public function __construct($dsn, $username, $password, $options = array()) {
$this->isConnected = true;
try {
$this->connection = new PDO($dsn, $username, $password, $options);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); //sets the default to return 'named' properties in array.
} catch (PDOException $e) {
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function disconnect() {
$this->connection = null;
$this->isConnected = false;
}
public function query($SQL) {
try {
$result = $this->connection->query($SQL);
return $result;
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
public function prepare($SQL, $params = array()) {
try {
$result = $this->connection->prepare($SQL);
$result->execute($params);
return $result;
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
}
How to use:
$dsn = 'mysql:dbname=databasename;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$db = new pdoConnection($dsn, $user, $password);
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
$result = $db->prepare($SQL, array(":username" => 'someone'));
while($row = $result->fetch())
{
echo $row['ID'];
echo $row['EMAIL'];
}
這篇關于如何用 PDO 替換 MySQL 函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!