![]() |
Does it matter how to code query?
I've seen couble ways ppl to code query but now I just have to ask it from here.
Below is three examples and question is: Does it really matter how to do it? example 1: Code:
$query = "SELECT * FROM ´mytable´ WHERE slogan = 'kicksass'";Code:
$query = mysql_query("SELECT * FROM ´mytable´ WHERE slogan = 'kicksass'") or die(mysql_error());Code:
$showme = mysql_fetch_array(mysql_query("SELECT * FROM ´mytable´ WHERE slogan = 'kickass'")) or die(mysql_error()); |
I guess there is no difference.
I use the example 2 method. But sometimes you need to use example 1 method, for example if you have lets say a news.php file and the sections are defined by ?s var. you have news.php?s=1 ; news.php?s=2, etc so to select the section a possibility is using a switch, assign to a var say $query the query. case1: $query = "select * from science"; case2: $query = "select * from sports"; ,etc and then you just do: mysql_query($query); So it depends on what are you using it for. The example 3 just make a die() (exit and prints an error msg.) Might be fine using it in a small script, but in bigger sites it's better make a custom error handler. |
Doesn't matter how you do it. How you do it is personal preference and your coding style.
|
Make sure you keep what ever you do consistent...
|
People code things different ways because they like the syntax. Aside from that it all about the least amount of typing. Example one is Copy and Paste for everything except for the query, so you could put it into a function, while example 2 is good for an inline look at the query (so you don't have to reference to the function). Example three is just...
|
To expand what I said earlier, I personally like the following:
PHP Code:
|
Quote:
PHP Code:
Anyways, ontopic: I prefer the way I did the query above. This way, if a query is not working you can just do: PHP Code:
:) |
I agree with maZtah; I prefer style #1, which keeps the SQL statement separate from the actual query call. If you need to look at the query or data embedded in it, it's simple to display the SQL statement by itself. If it's trapped within a function call (or worse, a couple of function calls), troubleshooting why the data isn't coming out the other end becomes exponentially more difficult. You wind up having to dissect into several pieces anyway.
Using sprintf() is also a good way to go, but don't rely on it alone to protect your database from SQL injection. Parameterized queries are also useful, if your database interface extension provides them. |
| All times are GMT. The time now is 12:03 AM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0