I've extended the PDO class to create a simple DB class and currently use prepare + execute for all queries run to the database, even the ones that do not have parameters (e.g. SELECT * FROM table).
The question is: is there a performance benefit to actually use PDO::query for simple queries that do not have parameters, instead of prepare/execute?
query runs a standard SQL statement without parameterized data. Best practice is to stick with prepared statements and execute for increased security. See also: Are PDO prepared statements sufficient to prevent SQL injection?
MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases.
Performance. While both PDO and MySQLi are quite fast, MySQLi performs insignificantly faster in benchmarks - ~2.5% for non-prepared statements, and ~6.5% for prepared ones. Still, the native MySQL extension is even faster than both of these.
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.
Yes, because when you call PDO::prepare
, the server must create a query plan and meta information for that query, then there is additional overhead to bind the specified parameters when you use PDO::execute
. So, to save this overhead and improve performance, you can use PDO::query
for queries without parameters.
However, depending on the scale and size of your application, and your server / host configuration (shared / private), you may or may not see any performance increase at all.
There is a measurable difference between doing any one thing two different ways in PHP. You should assess the value that each method has for you and create test cases to see if it is worth it for you to do things one way or another.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With