MySQL Relevance Ordering

Wednesday, November 4, 2015

I am trying to work out the best way to order search results, they need to be ordered as below, but it doesn't appear to work.



Could this be because the column rating is being selected but the user is not filling in an input named rating?



if(isset($_POST['search'])){
$lname = trim($_POST['lname']);
$address = trim($_POST['address']);
$street = trim($_POST['street']);
$city = trim($_POST['city']);
$county = trim($_POST['county']);

if($lname==""){
$error[] = "Provide Last Name.";
}elseif($address=""){
$error[] = "Provide House Number/Name.";
}elseif($street==""){
$error[] = "Provide Street.";
}elseif($city==""){
$error[] = "Provide City.";
}elseif($county==""){
$error[] = "Provide County.";
}else{
try{
$stmt = $conn->prepare("SELECT *
FROM clients
WHERE lname like :lname
AND address like :address
AND street like :street
AND city like :city
AND county like :county
ORDER BY rating
WHEN rating like 'badabusive' THEN 0
WHEN rating like 'badnopay' THEN 1
WHEN rating like 'cautionlate' THEN 2
WHEN rating like 'cautiondiscount' THEN 3
WHEN rating like 'cautionextra' THEN 4
WHEN rating like 'good' THEN 5
END, rating");

$stmt->execute(array("lname" => empty($lname) ? '%' : '%'. $lname .'%',
"address" => empty($address) ? '%' : '%'. $address .'%',
"street" => empty($street) ? '%' : '%'. $street .'%',
"city" => empty($city) ? '%' : '%'. $city .'%',
"county" => empty($county) ? '%' : '%'. $county .'%'));

$userRow = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$userRow){
if($user->reportsearch($id,$lname,$address,$street,$city,$county)){
$user->redirect('./results.php?new='.$lname.$street);
}
}else{
if($userRow['rating'] == 'badnopay'){
$user->redirect('./results.php?badnopay='.$lname.$street);
}
if($userRow['rating'] == 'cautionextra'){
$user->redirect('./results.php?cautionextra='.$lname.$street);
}
if($userRow['rating'] == 'cautiondiscount'){
$user->redirect('./results.php?cautiondiscount='.$lname.$street);
}
if($userRow['rating'] == 'cautionlate'){
$user->redirect('./results.php?cautionlate='.$lname.$street);
}
if($userRow['rating'] == 'good'){
$user->redirect('./results.php?good='.$lname.$street);
}
if($userRow['rating'] == 'badabusive'){
$user->redirect('./results.php?badabusive='.$lname.$street);
}
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
}


I am wanting the results to be shown in this order, so if I have multiple results which only have different ratings then I want them to show as ordered.



It is currently throwing me this error, but I don't see the issue in the code.




SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN rating like 'badabusive' THEN 0 WHEN rating like 'badnopay' THEN' at line 9


0 comments:

Post a Comment