Skip to content

Instantly share code, notes, and snippets.

@jazerix
Last active August 29, 2015 14:24
Show Gist options
  • Save jazerix/b9569685ee7034df8725 to your computer and use it in GitHub Desktop.
Save jazerix/b9569685ee7034df8725 to your computer and use it in GitHub Desktop.
<?php
/**
* @param $query The string you wish to search for
* @param array database columns to include in search
* @return string SQL where clause
*/
public function createWhereClause($query, array $fields)
{
$words = explode(' ', $query);
foreach ($fields as $field)
foreach ($words as $word)
{
if (isset($whereClause) && strlen($whereClause) > 0)
$whereClause .= ! isset($currentField) || $field == $currentField ? " AND $field LIKE \"%$word%\"" : ") OR ($field LIKE \"%$word%\"";
else
$whereClause = "WHERE ($field LIKE \"%$word%\"";
$currentField = $field;
}
return "$whereClause)";
}
/**
* createWhereClause('niels', ['username', 'email']); = WHERE (username LIKE "%niels%") OR (email LIKE "%niels%")
* createWhereClause('niels faurskov', ['username', 'email']); = WHERE (username LIKE "%niels%" AND username LIKE "%faurskov%") OR (email LIKE "%niels%" AND email LIKE "%faurskov%")
* createWhereClause('niels fau', ['username', 'email','fullname']); = WHERE (username LIKE "%niels%" AND username LIKE "%fau%") OR (email LIKE "%niels%" AND email LIKE "%fau%") OR (fullname LIKE "%niels%" AND fullname LIKE "%fau%")
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment