mysqli - PHP - Include variables on condition in mysqli_stmt_bind_param ← (PHP, MySQL)

one text

I'm writing a function for a search query. users can search with category and keyword. I also want to add an option to search all records or only user's records.

One of the field will always be there. either keyword or category.

Now I''m trying to make mysqli_stmt_bind_param adjust to the query.

With my current knowledge, I'm writing a lot of if/else if conditions.

Later one I'll be adding another field location. which means more if/else

Is there a better way to do this?

function filter_records($db, $fields, $keyword, $category, $status, $user = '')
{
  if (empty($keyword) and empty($category)) {
    return false;
  }

  $keyword = empty($keyword) ? "" : "%$keyword%";
  $keyword_query = !empty($keyword) ? "(title LIKE ? OR tagline LIKE ? OR description LIKE ? OR tags LIKE ?)" : '';
  $add_and = empty($keyword_query) ? '' : ' AND ';
  $category_query = !empty($category) ? "$add_and categories LIKE ?" : '';
  $user_query = !empty($user) ? 'AND user_id = ?' : '';

  $sql = "SELECT $fields FROM mc_listings WHERE $keyword_query $category_query $user_query AND status = ? ORDER BY id DESC";
  $stmt = mysqli_stmt_init($db);
  if (mysqli_stmt_prepare($stmt, $sql)) {
    mysqli_stmt_bind_param($stmt, 'sssssss', $keyword, $keyword, $keyword, $keyword, $category, $status, $user);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    mysqli_stmt_close($stmt);
    return $result;
  }

  return false;
}

Source