Accepting selected projects for Q2 2024 Check availability →
SERVER 02SYSTEM ONLINELAST SYNC: 03:17:44RSS 2.0 — ONLINE
HALF ASSEDTECHNICAL NOTES_
EST. 1999ISSUE 04.2BEST VIEWED AT 1024 × 768
TECHNICAL NOTES / PRACTICAL GUIDES / PHP & DATABASES / RECORD f6d8d3
[PHP & DATABASES]GUIDE

Moving PHP database queries to PDO

POSTED: 23.02.2006AUTHOR: ADMIN3 MIN READCOMMENTS: 0

PHP 5.1 includes PDO, but a working installation also needs the driver for the chosen database. Migrate one application path at a time and compare its results with the existing code. A common interface does not remove differences between database servers.

Record the environment

Check the PHP release, available PDO drivers, database version and connection character set. Keep connection credentials outside publicly served files. Set the intended error-handling mode explicitly and send diagnostic details to a protected log. Test an unavailable database so a connection failure produces a useful service message without exposing passwords or SQL.

Separate values from the SQL statement

Prepare a query such as SELECT title FROM products WHERE id = :id, then supply the validated value when executing it. Do not put quotes around the placeholder or concatenate the submitted value back into the statement. Use one placeholder per value and a distinct name for each occurrence to avoid driver-specific behaviour with repeated named parameters.

Keep identifiers under application control

A placeholder represents a value, not a table name, column name or SQL keyword. Map a requested sort order onto a short list of complete, known ORDER BY clauses. For an IN list, create the required number of value placeholders and bind the elements individually; one comma-separated string is still one value. Test empty lists separately.

Check the transaction boundary

Use beginTransaction, commit and rollBack around related writes only after confirming that the database and table types support them. MySQL MyISAM tables do not become transactional because the application uses PDO. Avoid schema changes inside a transaction intended to protect ordinary updates, since some databases commit implicitly around DDL. Exercise a failure between the first and second write.

Compare results and release gradually

Test missing rows, NULL values, apostrophes, non-ASCII text and repeated executions with different parameters. Do not assume rowCount gives a portable row total for SELECT queries; issue a suitable COUNT query when that number is required. Keep validation and HTML output escaping in place. Prepared statements address the SQL boundary, not every way the same value may later be used.

MIGRATION CHECK

Keep the connection encoding explicit using the mechanism supported by the installed driver and server. Verify a save-and-read round trip with accented names before moving the remaining queries.

References

PHP 5.1.0 release announcement

PHP manual: PDO::prepare

PHP manual: PDO transactions