开发者

$sql and $result - Reason for using both?

开发者 https://www.devze.com 2023-03-08 19:30 出处:网络
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 the

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 int开发者_如何学Goo mysql_query(). But there may be some other reason people are hiding.


It normally to make debugging easier as you go: if something is wrong with the SQL query for any reason, you can simply print the contents of the $sql variable.

Also, the contents of SQL queries can get pretty long and it looks rather unreadable to have it inside a function call past a certain length.


Well it leads to cleaner coding if there is an error.

If you have an error on line 151 and 151 is:

mysql_fetch_array(mysql_query("SELECT * FROM something")); //where is the error

That is much harder to read then:

Error on line 150 and lines 149 - 151 are:

$sql = "SELECT * FROM something";
$result = mysql_query($sql); // ahh the error is here
mysql_fetch_array($result);


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_query function.

For starters... you're using mysql_query directly? 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 like mysql_query($sql) rather than mysql_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:

$sql = ' FROM table_name WHERE `some_field` = 1';
$count = db::getField('SELECT COUNT(`id`) '.$sql);
$page_worth = db::getRows('SELECT `id`, `name` '.$sql.' LIMIT '.$page.', '.$per_page);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消