-1

I'm trying to do price ascending or descending filter in php, but it is not working. Could some one help to fix it? Thanks

<select name='sort'>
<option value='ASC'> Price Low to High </option>
<option value='DESC'> Price High to Low </option>

</select>
<?php 
$query = 'SELECT prd_price FROM products ORDER BY '.$_REQUEST['sort'];
$run_query = mysqli_query($con,$query);

$row = mysqli_fetch_array($run_query);
?>
Frog
  • 19
  • 1
  • 6
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Dec 05 '17 at 18:28
  • 1
    You don't know what's wrong because you don't check for errors in your code. Never assume the code is always going to work flawlessly. Use [`mysqli_error()`](http://php.net/manual/en/mysqli.error.php) to get a detailed error message from the database. – John Conde Dec 05 '17 at 18:28
  • 3
    Your SQL query doesn't actually indicate which field to sort on. – Alex Howansky Dec 05 '17 at 18:29
  • I'm so lost in mysql things, sorry guys... – Frog Dec 05 '17 at 18:31

1 Answers1

1

You can't do it like this. Cause your select is not processed.

When you read the php docs about $_REQUEST you see that it only processes the values of $_POST, $_GET and $_COOKIE.

If you would like to make this working, you could do something like this:

<form method="post">
    <select name="sort">
        <option value="asc">Price Low to High</option>
        <option value="desc">Prive High to Low</option>
    </select>
    <input type="submit" value="Sort">
</form>
<?php
// check if the server recieved a post:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if (isset($_POST['sort'])) {
        if ($_POST['sort'] == "asc") {
            $query = "SELECT prd_price FROM products ORDER BY prd_price ASC";
        } else {
            $query = "SELECT prd_price FROM products ORDER BY prd_price DESC";
        }
    }
    // execute query here.
}
?>

And try to avoid using $_REQUEST

Wouter075
  • 134
  • 6
  • Thanks, but when I click sort button, products are getting sorted randomly – Frog Dec 05 '17 at 19:25
  • Strange, the provided sql queries are correct, see [MySQL :: Sorting Rows](https://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html). Could you provide some more information about your database structure? – Wouter075 Dec 05 '17 at 19:44