user2551208
user2551208

Reputation: 55

PHP Variable into MySQL Query?

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!

Upvotes: 0

Views: 68

Answers (3)

David Houde
David Houde

Reputation: 4778

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');

Upvotes: 0

Cthulhu
Cthulhu

Reputation: 1372

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

Upvotes: 1

olegsv
olegsv

Reputation: 1462

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");

Upvotes: 2

Related Questions