开发者

Any value of separating a MySQL query into $query and $result?

开发者 https://www.devze.com 2023-04-08 17:31 出处:网络
I always see MySQL queries structured like this, 开发者_如何学运维even with the simplest of queries:

I always see MySQL queries structured like this, 开发者_如何学运维even with the simplest of queries:

$query = "SELECT * FROM table_name WHERE id = '1'";
$result = mysql_query($query);

Is there any value, time or otherwise in doing the above over a simple one line query such as?

$result = mysql_query("SELECT * FROM table_name WHERE id = '1'";

I've always used the former, as when I started using PHP I thought it best to simply copy everyone else, however now that I'm working on a fairly large (relative to my other work) application, I could cut out a significant amount of arbitrary coding if there's really no difference.


Generally, I like separating them because I can easily do print $query; when I'm trying to figure out why my query won't work. It's mostly a matter of personal preference.


With the first, it's easier to log the SQL in case something went wrong (and it's easier to spot typos, like a missing bracket).


Actually there is no difference at all except for one thing. If you put your query in seperate variable then you can reuse that. If any changes occur in query you just need to edit the query in variable


You can always create a custom function that takes in a query and runs it, and pass additional optional arguments in case you want it to return the query, or log the query to track any issues etc.


Is there any value, time or otherwise in doing the above over a simple one line query such as?

sure, as MSpreij said, you can examine your query in case of error.

I always see MySQL queries structured like this, even with the simplest of queries:

$query = "SELECT * FROM table_name WHERE id = '1'";
$result = mysql_query($query) or trigger_error(mysql_error()." ".$query);

this simple construct will save you a dozen whines in stackoverflow "what does it mean mysql_fetch_array(): supplied argument is not a valid MySQL result"

notice the additional part. This is called programming.
It will print your query automatically, in case of error, along with mysql error message. Or log it into error log in a live server with appropriate settings.

Without writing print $query; manually.

However, both methods are ugly as hell.

One should never use raw API functions at all.

It's ugly, unmaintainable, bloated and repetitive.

One should develop a library, a function to make a call more intelligent and less repetitive

$data = mydb_get_row("SELECT * FROM table_name WHERE id = 1");

having all the processing inside. with error handling, query logging, parameter checking and api functions calling.
yet as a true one-liner, not a silly one you were trying to achieve.

0

精彩评论

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