Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help setting up logic for advanced search parameters in PHP

I would like to create an advanced search form much like a job site would have one that would include criteria such as keyword, job type, min pay, max pay, category,sub category etc...

My problem is deciding on how best to set this up so if I have to add categories to the parameters I'm not having to modify a whole bunch of queries and functions etc...

My best guess would be to create some sort of associative array out of all of the potential parameters and reuse this array but for some reason I feel like it's a lot more complex than this. I am using CodeIgniter as an MVC framework if that makes any difference.

Does anybody have a suggestion as how best to set this up?

Keep in mind I will need to be generating links such as index.php?keyword=designer&job_type=2&min_pay=20&max_pay=30

I hope my question is not to vague.

like image 687
bigmike7801 Avatar asked Oct 12 '22 12:10

bigmike7801


2 Answers

I don't know if it's what you need, but I usually create some search class.

<?php
$search = new Search('people');
$search->minPay(1000);
$search->maxPay(4000);
$search->jobType('IT');
$results = $search->execute();

foreach ($results as $result)
{
  //whatever you want
}

?>

You can have all this methods, or have some mapping at __set() between method name and database field. The parameter passed to the constructor is the table where to do the main query. On the methods or mapping in the __set(), you have to take care of any needed join and the fields to join on.

like image 71
Carlos Campderrós Avatar answered Oct 18 '22 11:10

Carlos Campderrós


There are much more 'enterprise-level' ways of doing this, but for a small site this should be OK. There are lots more ActiveRecord methods you can use as necessary. CI will chain them for you to make an efficient SQL request.

if($this->input->get('min_pay')) {
  $this->db->where('min_pay <', $this->input->get('min_pay'));
}

if($this->input->get('keyword')) {
  $this->db->like($this->input->get('keyword'));
}

$query = $this->db->get('table_name');
foreach ($query->result() as $row) {
  echo $row->title;
}
like image 23
Dan Blows Avatar answered Oct 18 '22 11:10

Dan Blows