In documentation I can see ORDER BY expression is usually put at the end of the query, however, in my case, I want to order products by price first and then choose brands, as a result, I would add " AND product_brand IN" after ORDER BY product_price. Then PHP throw an error, i’m pretty sure it is because I put AND express after ORDER BY expression, how can I get over this?
if(isset($_POST['action'])) {
$keyword = $_POST['keyword'];
$output = "";
$query = "SELECT * FROM $keyword WHERE product_rating = '4.5'";
if (isset($_POST['general'])) {
$general_filter = implode("','", $_POST['general']);
switch ($general_filter) {
case 'all':
$query .= "";
break;
case 'low_to_high':
$query .= "ORDER BY product_new_price ASC";
break;
case 'high_to_low':
$query .= "ORDER BY product_new_price DESC";
break;
case 'name_ascending':
$query .= "ORDER BY product_title ASC";
break;
case 'name_descending':
$query .= "ORDER BY product_title DESC";
break;
case 'newest':
$query .= "ORDER BY product_date DESC";
break;
case 'top_seller':
$query .= "ORDER BY product_sold ASC";
break;
case 'available':
$query .= "AND product_status = '1'";
break;
}
}
if (isset($_POST['brand'])) {
$brand_filter = implode(",", $_POST['brand']);
if ($brand_filter == 'all') {
$query .= "";
}
else {
$query .= " AND product_brand IN ('$brand_filter')";
}
}
I search for hours on internet and still stuck.
2
Answers
SQL has a specific order of commands. It is not allowed to have the orderBy before a WHERE clause.
You can solve this by moving the second if-statement up:
You can’t add conditions after ORDER BY.
You should put those conditions in the WHERE clause.
Or if you want to ORDER BY more than one field just separate them with , .
Like:
ORDER BY product_title DESC, product_status = '1' ASC
and so on.