Skip to content

Instantly share code, notes, and snippets.

@jamierumbelow
Created April 10, 2013 22:02
Show Gist options
  • Save jamierumbelow/5358856 to your computer and use it in GitHub Desktop.
Save jamierumbelow/5358856 to your computer and use it in GitHub Desktop.
A quick multi-table multi-field search model for CI / PHP
<?php
class Search_model extends CI_Model
{
protected $tables = array(
'users' => array( 'name', 'email' )
);
public function run($search)
{
$queries = array();
foreach ($this->tables as $table => $fields)
{
$wheres = array();
$query = '(SELECT ';
$query .= implode(', ', $fields);
$query .= ", '" . $table . "' AS type";
$query .= " FROM " . $table;
foreach ($fields as $field)
{
$wheres[] = $field . ' LIKE "%' . $search . '%"';
}
$query .= ' WHERE ';
$query .= implode(' OR ', $wheres);
$query .= ')';
$queries[] = $query;
}
$result = $this->db->query(implode(' UNION ', $queries));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment