PHP PDO Tutorial to Connect MySql Database

How to connect MySql Database using PHP PDO (PHP Data Objects). What’s the advantage of using PHP data objects.

PHP PDO (PHP data objects) is a database access layer providing a uniform method of access to multiple databases. PHP Data Objects is written to provide a consistent API.  Before MySqli and PDO, we used MySql API to connect MySql Database. Let’s see how PDO is better than MySql Api.

Why PDO is better than MySql

1. It supports multiple databases using a 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 have worked in PHP, then you are familiar with MySQL API syntax.

In MySQL, we need to escape special characters to prevent our code from SQL injection. To prevent our code from SQL injection we use  mysql_real_escape_string() method. But in a Prepared Statement, we don’t need to worry about SQL Injection.

Let’s check the syntax of PDO.

In the PHP Data Objects syntax, We have mentioned driver name which is MySQL and then other details such as host, dbname, username and a password.

Error Handling in PDO

PDO provides us three error handling strategies.

1. PDO::ERRMODE_SILENT – This is a 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 error occurs. 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.

output:

2. PDO::FETCH_NUM

output:

3. PDO::FETCH_BOTH

output:

4. PDO::FETCH_OBJ

output:

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

Conclusion

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.

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.