Search code examples
phpmysqlmysql-error-1064mysql-error-1054

I need to search with multi variable and sort


I can search multiple value with mysql. I need to implement SORT BY on it

This is my coding which is working perfect

   $conditions = array();
if ($key) {
  $conditions[] = 'job_title LIKE "%'.$key.'%"';
}
if ($category) {
  $conditions[] = 'job_category = "'.$category.'"';
}
if ($location) {
  $conditions[] = 'job_location = "'.$location.'"';
}
if ($country) {
  $conditions[] = 'job_country = "'.$country.'"';
}
if ($salary) {
  $conditions[] = 'job_salary >= "'.$salary.'"';
}


$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON  jobs.job_category=job_category.category_id  '.implode(' AND ', $conditions);

When I apply SORT BY like this

if ($sort) 
{
$conditions[] = 'ORDER BY "'.$sort.'"';
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON  jobs.job_category=job_category.category_id  '.implode(' AND ', $conditions);
}
else
{
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON  jobs.job_category=job_category.category_id  '.implode(' AND ', $conditions);
}

result is

Blockquote SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id job_location = "Manjeri" AND ORDER BY "job_salary" Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/work/mobjob/test.php on line 41


Solution

  • you shouldn't implode your order by as a condition.. it's not one..

    just append it onto the end like so:

    $sqlStatement = 'SELECT * FROM jobs JOIN job_category ON  jobs.job_category=job_category.category_id  ';
    
    if( sizeof($conditions)) {
        $sqlStatement .= ' WHERE ' . implode(' AND ', $conditions);
    }
    
    
    
    if($sort) {
        $sqlStatement .= ' ORDER BY "'.$sort.'"';
    }