What is PDO and why should I use it?

People keep mentioning that I have to use PDO in my PHP when working with MySQL, which I have never heard of before.

What is PDO? How is it used and what are the pros and cons?

Thank,

+5
source share
3 answers

Consider PDO as a built-in class that comes bundled with PHP to make it easier to interact with your database. when developing a PHP application, you need to take care of a lot of things, such as establishing a connection, creating a query, getting the result of converting a resource into an array, avoiding MySQL Injection with mysql_real_escape_string(), now there are a lot of things that need to be taken care of at least, but not the last, consider the situation when you want to switch from mysql to mysqli or MSSQL, for which you need to go through each function and change each line of code according to your needs. PDO fixes this whole problem by providing one centralized class.

To develop, see below code.

Establish a connection to MySQL using PDO:

$dbh = new PDO('mysql:host='.HOST.';dbname='.DATABASE,USERNAME,PASSWORD); 

, , $dbh , , , .

$sth = $dbh->query('SELECT id,name,email FROM users');
$user = $sth->fetch(PDO::FETCH_ASSOC);

$user , .

, .

$sth = $dbh->prepare('INSERT INTO users(name,email) VALUES(:name, :email)');
$sth->bindParam(':name', 'My Name');
$sth->bindParam(':email', 'email@email.com');
$sth->execute();

placeholder, PDO , MySQL Injection. netttus, , PDO

http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

+14

http://php.net/manual/en/book.pdo.php

PHP (PDO) , PHP.

PDO , , , , . PDO ; SQL . , .

0

PDO - - MySQL. , PDO php ( ).

PDO , sql. , , PDO, , .

If you are not interested in security (e.g. SQL injection ), and you can write the natural MySQL queries that you need, then you need not worry about that. Learning this may make it easier to work in the future when you work on more structured projects using frameworks.

0
source

All Articles