jeudi 27 février 2020

My sql query for item search is not working

Im building a restaurant website and i have to search for food items according to what the user inputs in the search bar. I have to sort the results by the most relevant one

    $inpText=$_POST['searchValue']; //I have retrieved the value here and it works

    $searchData=test_input($inpText); //this is a function which removes extra characters
    $searchData=preg_replace("#[^0-9a-z]#i","",$searchData);
    $searchData=strtolower($searchData);


    $sql="SELECT * FROM food WHERE LOWER(Food_Name) LIKE '%$searchData%'
          ORDER BY CASE WHEN LOWER(Food_Name)='$searchData' THEN 0
                        WHEN LOWER(Food_Name)='$searchData%' THEN 1
                        WHEN LOWER(Food_Name)='%$searchData%' THEN 2
                        WHEN LOWER(Food_Name)='%$searchData' THEN 3
                        ELSE 4
          END";

          echo $sql;

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $res=$conn->query($sql);

UPDATED:

  $sql="SELECT * FROM food WHERE LOWER(Food_Name) OR LOWER(Food_Description) 
  LIKE '%$searchData%'
          ORDER BY CASE WHEN LOWER(Food_Name) OR LOWER(Food_Description) LIKE 
  '$searchData' THEN 0
                        WHEN LOWER(Food_Name) OR LOWER(Food_Description) LIKE 
  '$searchData%' THEN 1
                        WHEN LOWER(Food_Name) OR LOWER(Food_Description) LIKE 
  '%$searchData%' THEN 2
                        WHEN LOWER(Food_Name) OR LOWER(Food_Description) LIKE 
  '%$searchData' THEN 3
                 ELSE 4
          END";

I added food _description but this does not work




Aucun commentaire:

Enregistrer un commentaire