Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm having a small problem with my PHP code... I've searched on the forum and copied the code but I must be doing something wrong. I'm trying to order the results I'm getting on a page I have by name, year etc. using a variable. But it isn't working?

I've got this:

$orderby = 'name';    //'$_GET['orderby']' <---- I'd like to use this later to make it dynamic
$req = mysql_query('select id, name, year, genre, cover from table ORDER BY  `table`.`'$orderby'` ASC');

And why isn't the code working? It doesn't give me an error, the page just doesn't load and stays blank!

share|improve this question
    
What, no rants about using $_GET in queries and SQL injection yet? :) –  CompuChip Dec 28 '13 at 10:55
add comment

4 Answers

You forgot the concatenation :

$req = mysql_query('select id, name, year, genre, cover from table ORDER BY  `table`.`'.$orderby.'` ASC');

Or

$req = mysql_query("select id, name, year, genre, cover from table ORDER BY  `table`.`$orderby` ASC");
share|improve this answer
add comment

Change '$orderby' to '.$orderby.'. . is php concatenation operator.

share|improve this answer
add comment

Try

$req = mysql_query('select id, name, year, genre, cover from table ORDER BY  `table`.`' . $orderby . '` ASC');

or

$req = mysql_query('select id, name, year, genre, cover from table ORDER BY  `table`.`$orderby` ASC');
share|improve this answer
    
Second option (as it is now) won't work. –  Cthulhu Dec 28 '13 at 10:56
add comment

Oh QuoTaTiONs

$req = mysql_query("select id, name, year, genre, cover from table ORDER BY table.{$orderby} ASC");

Single quotes don't execute variables, but double quotes will do, and it's better to wrap them within {}

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.