0

I have variables coming from a query string (don't worry I did it safely). Please advise me how I can add the variables to my sql query. My variables:

$order = "ASC";
if(isset($_POST['sort'])){
    if($_POST['sort']=="date"){
        $sort = "date";
    }
    else if($_POST['sort']=="pricelow"){
        $sort = "Price";
    }
    else if($_POST['sort']=="pricehigh"){
        $sort = "Price";
        $order = "DESC";
    }
}

And my query below:

 mysql_query("SELECT * FROM event ORDER BY '$sort' '$order'");
pedrum golriz
  • 513
  • 8
  • 27
  • 5
    remove single quotes around `$sort` and `$order` –  Aug 31 '13 at 20:49
  • 2
    I am glad you ask. Please, [don't use mysql_* functions in new code](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about **Prepared Statements** instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). See [this article](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) for a quick overview how to do it and why it is so important. – juergen d Aug 31 '13 at 20:49
  • as for what Akam said field names don't get quoted neither do the ASC DESC keywords. Only time field names need "quoted" is with backticks and only when their names match mysql keywords – Patrick Evans Aug 31 '13 at 20:50

2 Answers2

0

I think you have it covered, just a simple change, remove the single quotes in the SQL from around the sort and order variables

mysql_query("SELECT * FROM event ORDER BY $sort $order")

Just a sidenote: mysql is deprecated, I would advise using mysqli or PDO

Joshua Kissoon
  • 3,269
  • 6
  • 32
  • 58
-2
mysql_query("SELECT * FROM event ORDER BY " . $sort . " " . $order);

Or, change your assignment like this:

$order = " DESC";

and you can use:

mysql_query("SELECT * FROM event ORDER BY " . $sort . $order);
DevlshOne
  • 8,357
  • 1
  • 29
  • 37
  • You need to have a space between the `SORT` and the `ORDER`. Either do it up above in your variables or here in your query. – DevlshOne Aug 31 '13 at 20:51