Why You Ought to Be Utilizing PHP’s PDO for Database Entry

Why You Should Be Using PHP's PDO for Database Access

Many PHP programmers realized entry databases through the use of both the MySQL or MySQLi extensions. As of PHP 5.1, there’s a greater approach. PHP Knowledge Objects (PDO) present strategies for ready statements and dealing with objects that can make you much more productive!

CRUD Turbines and Frameworks

Database code is repetitive, however crucial to get proper. That is the place PHP CRUD mills and frameworks are available—they prevent time by robotically producing all this repetitive code so you may give attention to different elements of the app. 

On CodeCanyon, you’ll find CRUD mills and frameworks that can assist you to ship excellent high quality merchandise on time. (CRUD is an acronym for create, learn, replace, and delete—the fundamental manipulations for a database.)

Introduction to PDO

PDO—PHP Knowledge Objects—are a database entry layer offering a uniform methodology of entry to a number of databases.

It does not account for database-specific syntax, however can enable for the method of switching databases and platforms to be pretty painless, just by switching the connection string in lots of cases.


This tutorial is not meant to be a whole how-to on SQL. It is written primarily for folks at the moment utilizing the mysql or mysqli extension to assist them make the bounce to the extra transportable and highly effective PDO.

In terms of database operations in PHP, PDO supplies a whole lot of benefits over the uncooked syntax. Let’s shortly record a number of:

  • abstraction layer
  • object-oriented syntax
  • assist for ready statements
  • higher exception dealing with
  • safe and reusable APIs
  • assist for all fashionable databases

Database Assist

The extension can assist any database {that a} PDO driver has been written for. On the time of this writing, the next database drivers can be found:

  • PDO_DBLIB (FreeTDS/Microsoft SQL Server/Sybase)
  • PDO_FIREBIRD (Firebird/Interbase 6)
  • PDO_INFORMIX (IBM Informix Dynamic Server)
  • PDO_MYSQL (MySQL 3.x/4.x/5.x)
  • PDO_OCI (Oracle Name Interface)
  • PDO_ODBC (ODBC v3 (IBM DB2, unixODBC, and win32 ODBC))
  • PDO_PGSQL (PostgreSQL)
  • PDO_SQLITE (SQLite 3 and SQLite 2)
  • PDO_4D (D)

All of those drivers are usually not essentially accessible in your system; this is a fast solution to discover out which drivers you have got:


Totally different databases might have barely completely different connection strategies. Beneath, you may see the strategy to connect with a number of the hottest databases. You may discover that the primary three are equivalent, apart from the database kind—after which SQLite has its personal syntax.

Connection StringConnection StringConnection String

Please pay attention to the attempt/catch block. You need to all the time wrap your PDO operations in a attempt/catch and use the exception mechanism—extra on this shortly. Usually, you are solely going to make a single connection—there are a number of listed to point out you the syntax. $DBH stands for ‘database deal with’ and might be used all through this tutorial.

You’ll be able to shut any connection by setting the deal with to null.

You may get extra info on database-specific choices and/or connection strings for different databases from PHP.internet.

Exceptions and PDO

PDO can use exceptions to deal with errors, which implies something you do with PDO ought to be wrapped in a attempt/catch block. You’ll be able to drive PDO into certainly one of three error modes by setting the error mode attribute in your newly created database deal with. This is the syntax:

It doesn’t matter what error mode you set, an error connecting will all the time produce an exception, and making a connection ought to all the time be contained in a attempt/catch block.


That is the default error mode. If you happen to depart it on this mode, you will should examine for errors in the best way you are most likely used to if you happen to’ve used the mysql or mysqli extensions. The opposite two strategies are extra appropriate for DRY programming.


This mode will difficulty a regular PHP warning and permit this system to proceed execution. It is helpful for debugging.


That is the mode you need in most conditions. It fires an exception, permitting you to deal with errors gracefully and conceal information which may assist somebody exploit your system. This is an instance of profiting from exceptions:

There’s an intentional error within the choose assertion; it will trigger an exception. The exception sends the main points of the error to a log file and shows a pleasant (or not so pleasant) message to the person.

Insert and Replace

Inserting new information (or updating present information) is without doubt one of the extra frequent database operations. Utilizing PHP PDO, that is usually a two-step course of. All the things lined on this part applies equally to each the UPDATE and INSERT operations.

Prepare Bind and ExecutePrepare Bind and ExecutePrepare Bind and Execute

This is an instance of essentially the most primary kind of insert:

You possibly can additionally accomplish the identical operation through the use of the exec() methodology, with one much less name. In most conditions, you are going to use the longer methodology so you may benefit from ready statements. Even if you happen to’re solely going to make use of it as soon as, utilizing ready statements will assist defend you from SQL injection assaults.

Ready Statements

Utilizing ready statements will assist defend you from SQL injection.

A ready assertion is a pre-compiled SQL assertion that may be executed a number of occasions by sending simply the information to the server. It has the added benefit of robotically making the information used within the placeholders secure from SQL injection assaults.

You utilize a ready assertion by together with placeholders in your SQL. Listed here are three examples: one with out placeholders, one with unnamed placeholders, and one with named placeholders.

You need to keep away from the primary methodology; it is right here for comparability. The selection of utilizing named or unnamed placeholders will have an effect on the way you set information for these statements.

Unnamed Placeholders

There are two steps right here. First, we assign variables to the assorted placeholders (strains 2–4). Then, we assign values to these placeholders and execute the assertion. To ship one other set of knowledge, simply change the values of these variables and execute the assertion once more.

Does this appear a bit unwieldy for statements with a whole lot of parameters? It’s. Nevertheless, in case your information is saved in an array, there’s a simple shortcut:

That is simple!

The info within the array applies to the placeholders so as. $information[0] goes into the primary placeholder, $information[1] the second, and many others. Nevertheless, in case your array indexes are usually not so as, this would possibly not work correctly, and you will have to re-index the array.

Named Placeholders

You possibly can most likely guess the syntax, however this is an instance:

You should utilize a shortcut right here as effectively, however it works with associative arrays. This is an instance:

The keys of your array don’t want to begin with a colon, however in any other case have to match the named placeholders. You probably have an array of arrays, you may iterate over them and easily name the execute with every array of knowledge.

One other good characteristic of named placeholders is the flexibility to insert objects straight into your database, assuming the properties match the named fields. This is an instance object, and the way you’d carry out your insert:

Casting the item to an array within the execute signifies that the properties are handled as array keys.

Choosing Knowledge

Selecting DataSelecting DataSelecting Data

Knowledge is obtained through the ->fetch(), a technique of your assertion deal with. Earlier than calling fetch, it is best to inform PDO how you need the information to be fetched. You will have the next choices:

  • PDO::FETCH_ASSOC: returns an array listed by column title.
  • PDO::FETCH_BOTH (default): returns an array listed by each column title and quantity.
  • PDO::FETCH_BOUND: assigns the values of your columns to the variables set with the ->bindColumn() methodology.
  • PDO::FETCH_CLASS: assigns the values of your columns to properties of the named class. It can create the properties if matching properties don’t exist.
  • PDO::FETCH_INTO: updates an present occasion of the named class.
  • PDO::FETCH_LAZY: combines PDO::FETCH_BOTH/PDO::FETCH_OBJ, creating the item variable names as they’re used.
  • PDO::FETCH_NUM: returns an array listed by column quantity.
  • PDO::FETCH_OBJ: returns an nameless object with property names that correspond to the column names.

In actuality, there are three which can cowl most conditions: FETCH_ASSOCFETCH_CLASS, and FETCH_OBJ. To be able to set the fetch methodology, the next syntax is used:

You can even set the fetch kind straight inside the ->fetch() methodology name.


This fetch kind creates an associative array, listed by column title. This ought to be fairly acquainted to anybody who has used the mysql/mysqli extensions. This is an instance of choosing information with this methodology:

The whereas loop will proceed to undergo the end result set one row at a time till full.


This fetch kind creates an object of std class for every row of fetched information. This is an instance:


The properties of your object are set BEFORE the constructor known as. That is essential.

This fetch methodology lets you fetch information straight into a category of your selecting. Once you use FETCH_CLASS, the properties of your object are set BEFORE the constructor known as. Learn that once more—it is essential. If properties matching the column names do not exist, these properties might be created (as public) for you.

Because of this in case your information wants any transformation after it comes out of the database, it may be finished robotically by your object as every object is created.

For example, think about a scenario the place the deal with must be partially obscured for every file. We might do that by working on that property within the constructor. This is an instance:

As information is fetched into this class, the deal with has all its lowercase a-z letters changed by the letter x. Now, utilizing the category and having that information rework happen is totally clear:

If the deal with was ‘5 Rosebud,’ you’d see ‘5 Rxxxxxx’ as your output. After all, there could also be conditions the place you need the constructor known as earlier than the information is assigned. PDO has you lined for this, too.

Now, once you repeat the earlier instance with this fetch mode (PDO::FETCH_PROPS_LATE), the deal with will not be obscured, because the constructor was known as and the properties had been assigned.

Lastly, if you actually need to, you may move arguments to the constructor when fetching information into objects with PDO:

If it’s essential to move completely different information to the constructor for every object, you may set the fetch mode contained in the fetch methodology:

Some Different Useful Strategies

Whereas this is not meant to cowl every thing in PDO (it is an enormous extension!), there are a number of extra strategies you will need to know to be able to do staple items with PDO.

The ->lastInsertId() methodology is all the time known as on the database deal with, not the assertion deal with, and can return the auto-incremented id of the final inserted row by that connection.

The ->exec() methodology is used for operations that can’t return information apart from the affected rows. The above are two examples of utilizing the exec methodology.

The ->quote() methodology quotes strings so they’re secure to make use of in queries. That is your fallback if you happen to’re not utilizing ready statements.

The ->rowCount() methodology returns an integer indicating the variety of rows affected by an operation. In at the least one identified model of PDO, the strategy was not working with choose statements. Nevertheless, it does work correctly in model PHP 5.1.6 and above.

If you happen to’re having this drawback and may’t improve PHP, you can get the variety of rows with the next:

PHP CRUD Turbines From CodeCanyon

It can save you your self hours of time by discovering a PHP CRUD generator from CodeCanyon and utilizing it in your initiatives. Listed here are 5 of the most well-liked downloads you can begin utilizing proper now.

1. xCRUD: Knowledge Administration System (PHP CRUD)

We begin with xCRUD, which is an easy and highly effective PHP CRUD generator. It gives many nice options, like a multi-instance system, a quick AJAX interface, and extra. xCRUD can also be simple to make use of if you happen to’re not a seasoned programmer.

2. Laravel Multi-Objective Utility: Sximo 6

The Sximo 6 builder is predicated on the most well-liked frameworks round. It is also acquired a contemporary replace for 2021, making it as simple to make use of and feature-rich as attainable. A few of these options embrace:

  • database desk administration
  • front-end and back-end templates
  • module MySQL editor
  • a number of pictures and file add assist

Attempt it if you happen to’re seeking to save time with a CRUD PHP template.

3. PDO Crud: Type Builder & Database Administration

This is one other highly effective CRUD PHP generator. This PHP PDO code template does database administration effectively. However that is not all it does. You can even use PDO CRUD to construct useful varieties straight out of your database tables. It is a helpful characteristic that not many different choices have.

4. Cicool: Web page, Type, Relaxation API and CRUD Generator

Cicool is one other multipurpose builder price wanting into. Not solely does it provide a CRUD builder, however it additionally has a:

  • web page builder
  • kind builder
  • relaxation API builder

On prime of those options, it’s also possible to add extensions to Cicool and simply customise its theme.

5. PHP CRUD Generator

Straightforward admin panel builder? Test. Straightforward-to-navigate interface? Test. In-depth database evaluation? One other examine. This PHP CRUD generator has every thing it’s essential to construct nice dashboards and retailer your information. With completely different person authentication and rights administration options, this PDO PHP template is price trying out.


I hope this helps you migrate away from the mysql and mysqli extensions. What do you suppose? Are there any of you on the market who would possibly make the swap?

If you want to construct a fast CRUD interface with PHP and PDO, check out the next posts!

Leave a Reply

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

Related Posts