Just trying to improve the efficiency of my code so a simply question:
I see quite often people declare their SQL query using one var ($sql) and then putting the result into another ($result). Is there any reason people do this apart from keeping things slightly tidier? I presume it’s slightler better just to put the SQL query straight into mysql_query(). But there may be some other reason people are hiding.
There isn’t anything magical about it. Putting your SQL into a variable has a lot of upsides and very few downsides; the same cannot be said for passing your SQL query straight to the
mysql_queryfunction.For starters… you’re using
mysql_querydirectly? Most developers are going to have wrapped such functions into some kind of database object/controller, or they’re going to use PDO or the like. In any event, putting the SQL into a variable allows you to easily swap out the thing you’re passing the SQL to. When I update code to switch database access methodology, it makes it easier if I am changing a line likemysql_query($sql)rather thanmysql_query('SELECT .... SUPER LONG QUERY ...').When debugging, one can simply
echo($sql). If one wants to do a count query separate from the data query:And so on, and so on. It really does boil down to preference, but I find this approach much more flexible and rapidly adaptable/debuggable.