Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is PDO & why should I use it?

Tags:

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.

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

Thanks,

like image 794
DaveB Avatar asked Aug 08 '11 10:08

DaveB


1 Answers

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.

to establish a connection to MySQL Using PDO :

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

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);

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 protected]');
$sth->execute();

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/

like image 93
Ibrahim Azhar Armar Avatar answered Sep 28 '22 20:09

Ibrahim Azhar Armar