By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,060 Members | 1,878 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,060 IT Pros & Developers. It's quick & easy.

Dynamic MySQL query is supposed to order by column name (variable), but won't

P: 24
I am currently working on a project where I need to sort my MYSQL query results by different categories. How ever the code does not seem to be working properly and I spend too much time on it already.

So here is the code:

[PHP]
if (isset($_GET['sortby'])){$sort = $_GET['sortby'];}
else $sort = '';

$query = "SELECT * FROM list WHERE county = '$counties[$x]' order by '$sort' ";
$db->query($query);
[/PHP]

When I view the results I dont the order I want, the order I posted $_GET

how ever when I let the query be lets say "bandwidth"

[PHP] $query = "SELECT * FROM list WHERE county = '$counties[$x]' order by bandwidth ";[/PHP]

it works.

can you help me where am I going wrong.
Sep 4 '07 #1
Share this Question
Share on Google+
6 Replies


epots9
Expert 100+
P: 1,351
order by has to be followed by a column name, your $sort isn't a column name.
Sep 4 '07 #2

pbmods
Expert 5K+
P: 5,821
Heya, Irish.

Changed thread title to better describe the problem (did you know that threads whose titles do not follow the Posting Guidelines actually get FEWER responses?).

Try using backticks (`) around $sort instead of quotes (').
Sep 4 '07 #3

P: 24
$sort is actually a variable and could be anything, by any coloumn name I want. But what ever way it reads or parses it, mysql does not seem to be able to get the information from the variable. I tried the backsticks but they dont work I only get an error when I try to fetch the results. using mysql_fetch.

CAN ANYONE HELP ME IT IS NOT WORKING!!

thanks
Sep 4 '07 #4

Atli
Expert 5K+
P: 5,058
The order by clause requires the name of a column that exists in the table. The column name should not be quoted. You can encapsulate the column name in backticks (`), as pbmods suggested.

Note, that depending on your server and how you created the table, the column names may be case-sensitive.
(My tests show that columns created using backticks are case-sensitive, whether they are encapsulated in the SELECT query or not)

If your $sort variable provides a value that fits this description, your query should run fine. If not, it will fail.
Sep 5 '07 #5

P: 24
Thanks I fixed the problem
Sep 5 '07 #6

pbmods
Expert 5K+
P: 5,821
Heya, Irish.

Glad to hear you got it working! Good luck with your project, and if you ever need anything, post back anytime :)
Sep 5 '07 #7

Post your reply

Sign in to post your reply or Sign up for a free account.