PDO Tutorial in PHP to Connect MySql Database

PDO refers to PHP Data Objects. It is a database access layer providing a uniform method of access to multiple databases.PHP Data Objects is written to provide consistent API. It means in future if you change your database, the code changes is very minimal.

Why PDO is better than MySql

1. It supports multiple database using single interface.

2. PHP Data Objects uses prepared statement so you don’t need to worry about sql injection.

3. It provides consistent error handling.

4. Most important MySql extension is deprecated as of PHP 5.5.0, and will be removed in the future

If you worked in PHP, then you are familiar with mysql syntax.

In mysql if you want to escape special characters to prevent your code from sql injection, you need to use mysql_real_escape_string function. But in Prepared Statement you don’t need to worry about Sql Injection.

Let’s check the PDO syntax

In the PHP Data Objects syntax first i used driver name which is mysql and then the required details such as host,dbname,username and password.

Error Handling in PDO

It has three error handling strategies

1. PDO::ERRMODE_SILENT – This is default mode. If you don’t set any error mode it will set this as default.

2. PDO::ERRMODE_WARNING – throws PHP Warnings

3. PDO::ERRMODE_EXCEPTION – throws Exception when they occur. Always use this mode during development.

PDO Fetch Modes

To Fetch a result, It provides following choices.

1. PDO::FETCH_ASSOC – It returns an array. In above example i use this one.








Fetch Mode Complete Documentation

Insert Operation

Inserting new data or updating a data using PHP Data Objects works in three steps first it prepares, then bind and finally execute.

i) Prepare
ii) Bind
iii) Execute


If you are working on some PHP projects, try to use Prepared Statements as it is much better than MySql api. If you have any comments or suggestions for the improvement please let us know.

Kumar Singh

About Kumar Singh

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.

4 Responses to PDO Tutorial in PHP to Connect MySql Database

  1. Pingback: What is SQL Injection and How to Prevent SQL Injection

  2. Pingback: MySqli Tutorial:PHP MySqli Extension

  3. Pingback: Difference Between MyISAM and InnoDB Storage Engines

  4. Pingback: How to access/connect mysql database in php.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">