Kamikaza
Kamikaza

Reputation: 635

PHP Echo _GET value to MySQL and filter results

I have a search result page with a simple form to filter order of results, I want the form to filter:

ORDER BY - ASC or DESC - and PER PAGE LIMIT in the MySQL query

Here is the code to filter the order by I am trying to use

$order_by = mysqli_real_escape_string($database,$_GET['order_method']);
$query = mysqli_query($database,"SELECT * FROM `products` 
order by `<?php if(empty($order_by)){echo "id";}else{echo "$order_by"; ?>` ASC");

It is not working ... I get errors in >php line 22 and this line is the line of code above

The idea is that if the user comes to the default page I obviously get no $order_by so in this case the order by will be the default

echo "id"

But if the customer uses the html form to filter the results and I get the "order_by" the mysql query order by changes to the value the customer sends using the html form in this case

echo "$order_by"

I am trying many ways to do this but no one seems to work, any ideas would help a lot

Upvotes: 0

Views: 172

Answers (1)

RichardAtHome
RichardAtHome

Reputation: 4313

Your code:

$order_by = mysqli_real_escape_string($database,$_GET['order_method']);
$query = mysqli_query($database,"SELECT * FROM `products` 
order by `<?php if(empty($order_by)){echo "id";}else{echo "$order_by"; ?>` ASC");

The problem:

<?php if(empty($order_by)){echo "id";}else{echo "$order_by"; ?>

You are already in a PHP code block. You need to build up the query string using concatenation:

Try:

$order_by = mysqli_real_escape_string($database,$_GET['order_method']);

$sql = "SELECT * FROM `products` order by `";

if(empty($order_by)){
  $sql .= "id";
} else {
  $sql .= $order_by;
}

$sql .="` ASC";

// Now you can execute the query
$query = mysqli_query($database,$query);    

Upvotes: 1

Related Questions