Ian Y. Ian Y. - 6 months ago 36
PHP Question

Quotes and curly brakets around variables. Which one makes the fastest Mysql query?

We know that single quotes in PHP is faster than double quotes so

$foo = 'lorem ipsum';
is faster than
$foo = "lorem ipsum";

But what about in Mysql query? Does single quotes or double quotes affect the execution speed?

Consider the following different syntaxes. Which one is the fastest one? Or is there yet another syntax which is even faster?

mysqli_query($conn, 'SELECT * FROM `mytable` WHERE `full_name` = "' . $full_name. '"');

mysqli_query($conn, "SELECT * FROM `mytable` WHERE `full_name` = '" . $full_name. "'");

mysqli_query($conn, "SELECT * FROM `mytable` WHERE `full_name` = '$full_name'");

mysqli_query($conn, "SELECT * FROM `mytable` WHERE `full_name` = '{$full_name}'");

== Edit ==

I understand that the structure of database and other factors can also affect the execution speed. But let's assume that we already have a well-structured database and exclude other factors.

Answer Source

You are asking about MySQL when MySQL is not involved.

mysqli_query() takes two parameters, a connection to the DB and a query to execute.

The query is a simple string, that you can build however you want.

What you really asking is "what is the fastest way to construct my query string", which is explained in Speed difference in using inline strings vs concatenation in php5? (short answer: concatenation using single quotes).

Another way to construct your query is using prepared statements, which will be slower for a single query (you need to call two functions), but a lot faster when repeating the same query with different parameters.

Regarding the use of quotes within MySQL itself:

SELECT * FROM aTable WHERE a = 'blah';


SELECT * FROM aTable WHERE a = "blah";

It also has been answered in SO previously, take a look at When to use single quotes, double quotes, and backticks in MySQL (short answer regarding single/double, makes no difference, single quotes is the standard)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download