問題描述
人們不斷提到我在處理 MySQL 時應該在我的 PHP 中使用 PDO,我以前從未聽說過.
People keep on mentioning that I should be using PDO in my PHP when dealing with MySQL, I have never heard of this before.
什么是 PDO?它是如何使用的,有什么優點和缺點?
What is PDO? How is it used and what are the pros and cons?
謝謝,
推薦答案
將 PDO 視為一個內置類,它與 PHP 一起打包,可以讓您更輕松地與數據庫進行交互.在開發 PHP 應用程序時,您需要處理很多事情,例如建立連接、創建查詢、獲取結果、將資源轉換為數組、使用 mysql_real_escape_string()
逃避 MySQL 注入,現在這是一個有很多事情需要處理,至少但不是最后考慮這樣一種情況,您想從 mysql 跳轉到 mysqli 或 MSSQL,因為您需要遍歷每個函數并更改每一行代碼以滿足需要.PDO 通過提供一個集中的類來消除所有這些問題.
Consider PDO as a built in class that comes packaged with PHP to make it very easier for you to interact with your database. while developing a PHP Application you need to take care of lots of things like establish a connection, create query, to fetch the result convert resource into an array, escape MySQL Injection using mysql_real_escape_string()
now that is a lot of things to be taken care of, least but not the last consider a situation where you want to jump from mysql to mysqli or MSSQL for that you need to go through each and every function and change every line of code to suit the need. PDO eradicate all this problem by providing one centralized class.
詳細看下面的代碼.
使用 PDO 建立到 MySQL 的連接:
to establish a connection to MySQL Using PDO :
$dbh = new PDO('mysql:host='.HOST.';dbname='.DATABASE,USERNAME,PASSWORD);
就是這樣,連接建立,您可以重用 $dbh 來執行查詢,例如從表用戶獲取結果,您只需要兩行代碼.
that's it, the connection is established and you could reuse $dbh for performing queries for example to fetch the result from a table user you just need two line of code.
$sth = $dbh->query('SELECT id,name,email FROM users');
$user = $sth->fetch(PDO::FETCH_ASSOC);
現在 $user
會將所有值作為關聯數組獲取.
Now $user
will have all the values fetched as an associative array.
要將值插入數據庫,您需要執行以下操作.
To Insert value into the database you need to do the following.
$sth = $dbh->prepare('INSERT INTO users(name,email) VALUES(:name, :email)');
$sth->bindParam(':name', 'My Name');
$sth->bindParam(':email', 'email@email.com');
$sth->execute();
上面的代碼使用了命名占位符,這樣 PDO 可以讓你遠離許多漏洞,因為它可以讓你遠離 MySQL 注入.為了讓你開始,看看 netttus 的這個教程,他們解釋得很好,這篇文章將解釋你所有關于 PDO 的困境
The above code is using named placeholder, this way PDO will keep you safe from many vulnerabilities as it will keep you away from MySQL Injection. to get you started have a look at this tutorial by netttus, they have explained it very nicely, this article will explain all your dilemmas regarding PDO
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
這篇關于什么是 PDO &我為什么要使用它?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!