The biggest difficulty is prepare the "LIKE" clause appropriately, since the user can type "%" or other characters with special meaning in your search.
function like($string, $e)
{
return str_replace(array($e, '_', '%'), array($e.$e, $e.'_', $e.'%'), $string);
}
function like_clauses($campo, $termos)
{
$clauses = array();
foreach ($termos as $termo)
{
$clause =
'(' . $campo
. ' LIKE "%'
. mysqli_real_escape_string(like($termo, '='))
. '%" ESCAPE "=")';
$clauses[] = $clause;
}
return $clauses;
}
We can use the function like_clauses
above, stating the name of the field for search and a list of words (terms), to obtain the respective clauses "LIKE" appropriately formatted.
function minha_busca($busca)
{
$termos = array();
foreach (explode(' ', $busca) as $palavra)
{
$termo = trim($palavra);
if (!empty($termo))
{
$termos[] = $termo;
}
}
$termos = array_unique($termos);
if (empty($termos))
{
return array();
}
// até aqui apenas limpamos a entrada
// garantindo a existência de pelo menos um termo de busca
$sql = sprintf(
'SELECT item_brand_id FROM marcas WHERE %s',
implode(' OR ', like_clauses('item_brand_name', $termos))
);
// com este primeiro SELECT, obtemos as MARCAS
$brand_ids = array();
/* rodar SQL, fazer loop nos resultados, incluir os item_brand_ids em $brand_ids */
$sql = sprintf(
'SELECT * FROM produto WHERE %s AND (%s)',
empty($brand_ids) ? 'TRUE' : 'item_brand_id IN (' . implode(', ', $brand_ids) . ')',
implode(' OR ', like_clauses('item_name', $termos))
);
// com este segundo SELECT, obtemos os produtos, restringidos (ou não) pelas marcas
$produtos = array();
/* rodar SQL, fazer loop nos resultados, incluir os registros em $produtos */
return $produtos;
}
To use the function minha_busca
above, and check the results:
$busca = $_POST['busca'];
$resultado = minha_busca($busca);
print_r($resultado);
Remarks:
The use of mysqli_real_escape_string
assumes that the extension mysqli
is in use, with an active connection.
In function minha_busca
still need to fill in the code that executes the SQL and makes the loops in the results.
You can describe your tables here in the language
SQL
?– Leonel Sanches da Silva
Gypsy Morrison Mendez, as you can see, I take the table id marks and put in the product.
– Leandro Costa
I suggest you create indexes in the fields that will be subject to the search, for performance reasons. Since you are not using foreign keys, you can change the engine to Myisam and use full text Index.
– Henrique Barcelos
@Henriquebarcelos, but FULL TEXT does not work in the version of mysql I am using. knows some other method?
– Leandro Costa
Which version do you use?
– Henrique Barcelos