简体   繁体   中英

Variable MySql Query SORT BY and ORDER

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM