Liberator Liberator - 10 months ago 37
HTML Question

Building a mysqli query with order by and per page to show

The page display all results, now I want to filter results and how many results per page. To do this the visitor use a simple html GET form to select the filter.

Now I get the GET form and try to filter the results

$order_by = mysqli_real_escape_string($database,$_GET['order_by']);
$order = if(empty($order_by)){echo 'manufacturer';}else{echo '$order_by';

OK now we get the filter and try to get results from MySQL like this

$set_order=mysqli_query($database,"SELECT * FROM `products` order by `$order` ASC");}

But I get error in the line:

$order = if(empty($order_by)){echo 'manufacturer';}else{echo '$order_by';

Cannot find a way to do this ... Any idea?


First, set a default value for order by.

$order = 'manufacturer';

Next, if the user has provided something else, replace the default value with that.

if (!empty($_GET['order_by'])) {
    $order = mysqli_real_escape_string($database, $_GET['order_by']);

Then you can use whatever it ends up being in your query.

$set_order = mysqli_query($database, "SELECT * FROM `products` order by `$order` ASC");

It is definitely good that you're using mysqli_real_escape_string here, but I would recommend checking the user input against a list of acceptable column names to mitigate the SQL injection risk.