什么是PDO&我为什么要使用它? [英] What is PDO & why should I use it?

查看:70
本文介绍了什么是PDO&我为什么要使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们不断提到我在与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 Injection,现在要注意很多事情至少但不是最后一种情况,您需要从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.

详细说明一下下面的代码.

To elaborate have a look at below code.

使用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 Injection.为了让您入门,请看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/为什么要使用phps-pdo-for-database-access/

这篇关于什么是PDO&我为什么要使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆