PHP SQL MySQL – Why Put SQL Statement in a Variable Before Using mysql_query()?

MySQLPHPsql

I'm been working with PHP on and off for a bit now, and I've seen plenty of code both ways:

$sql = "SELECT …"; 
mysql_query($sql);

vs

mysql_query("SELECT…");

Is there a reason for separating the two, beyond being able to also pass in something such as $con?

Best Answer

There are a few reasons to do that:

  1. Readability: it may not apply with a simple mysql_query("SELECT…"); (by the way, aren't you expected to use PDO? It's not year 1998!). But you see the usefulness of this when it comes to multiline arguments. When you have several of these, things become even harder to read.

  2. Refactoring: it's really minor, but may apply as well. Imagine you will get the query from a config file instead of hardcoding it. It would probably be easier/more readable to have a variable defined first, then used as an argument.

  3. Debugging: imagine the query is generated (the thing you must never done, but well, it's another subject). If you want to set the breakpoint after the query is generated but before the query is done, it would be possible to do only if the query is actually assigned to a variable.

  4. Tracing: this may be a temporary code, and the author may know that he will add tracing of a query later.

In other words:

$sql = "SELECT …";
mysql_query($sql);

will become:

$sql = "SELECT …";
$this->trace(123, TRACE_INFORMATION, 'Running the query ' . $sql . '.');
mysql_query($sql);
Related Topic