Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO::query vs. PDOStatement::execute (PHP and MySQL)

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?

like image 871
pmm Avatar asked Feb 10 '12 19:02

pmm


People also ask

What is the difference between PDO query vs 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?

What is the difference between using MySQL functions and PDO?

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.

Is PDO faster than MySQLi?

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.

Does PDO work with MySQL?

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.


2 Answers

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.

like image 128
nickb Avatar answered Sep 20 '22 16:09

nickb


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.

like image 28
PFY Avatar answered Sep 22 '22 16:09

PFY