Most PHP programmers have discovered how to use MySQLi and MySQL extensions. However, PHP Data Objects (PDO) offer ways to work with objects and retrieve prepared statements which make work much easier.
PDO is a database access tool in PHP which enables uniform access across multiple databases. It does not support syntaxes specific to databases, but it permits relatively seamless switching between different platforms and databases, which can simply be done by changing the connection string.
Below is a little information about PDO, mainly directed at programmers who are still using MySQL and MySQLi extensions, outlining the superiority of the former. Different aspects will be studied in the next few paragraphs.
The PDO extension has the capability to access any database which the PDO driver has been written for. There are many PDO drivers available, a few of which include PDO drivers meant to access Free TDS, Sybase, Microsoft SQL Server, IBM DB2, Firebird/Interbase 6, Oracle Call Interface and PostgreSQL databases, among many more.
The drivers are not automatically available in every system, so you will have to find your available drivers and add the ones that you need.
There are different syntaxes to establish database connections which depend on specific databases. When using PDO, you want to ensure that your operations are wrapped in try/catch blocks and that you utilise the exception technique.
In normal cases, only a single connection need be made, and connections are closed by programming the database handle as a null. You can look up more specific options and syntaxes in various resource sites.
PDO allows for the use of exceptions for error-handling, which is why you’re advised to wrap PDO in try/catch blocks. This way, PDO can be forced into the relevant error mode attribute in order to produce an exception.
There are three – silent (default), warning and exception – modes. The latter two are more useful in DRY programming. ‘Warning’ error mode is useful for debugging and the ‘exception’ mode allows graceful error handling while hiding data that a person might use to exploit your system.
Inserts and Updates
PDO condenses the common insert and update database operations into a simple two-step process: Prepare >> [Bind] >> Execute. With this method, you can take full advantage of PDO’s prepared statements, which offer you protection against malicious attacks through SQL injection.
Prepared statements are pre-complied SQL statements which may be executed several times by sending this data to the servers. They are advantageous in that data used within the placeholders is automatically protected from SQL injection attacks.
There are many more features of PDO that make it superior to both MySQL and MySQLi; the above are only a tip of the iceberg. While MySQL was a useful tool in its time, no doubt it has been overtaken by the superiority of PDO objects, and PHP programmers would be better served by adopting this approach going forward.