Created
April 10, 2013 22:02
-
-
Save jamierumbelow/5358856 to your computer and use it in GitHub Desktop.
A quick multi-table multi-field search model for CI / PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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