Your query is not a valid query, and therefore the mysqli_query
is a BOOLEAN
, in this case false
.
You have other problems in the code. Dates or cycle here foreach ($v as $key => $value);
, instead of adding in the query more conditions OR
for each item in $pesquisa
.
I think what you want is to have multiple possibilities for descricao
and grau
depending on what was searched, type algo para pesquisar
would create 3 combinations, one for each word.
$pesquisa = $_POST["pesquisa"];
$v = explode(" ", $pesquisa);
$condicoes = []; // um array para guardar todas as condicoes
foreach ($v as $key => $value) {
// adicionar ao array uma condicao por cada valor passado em $pesquisa
$condicoes[] = "descricao LIKE '%{$value}%' OR grau LIKE '%{$value}%'";
}
$sql = "SELECT * FROM lentes WHERE " . implode(" OR ", $condicoes);
$resultado = mysqli_query($con, $sql);
// ... o resto do teu código
How it works
PHP eats arrays for breakfast, so be one of the most useful data structures in the language, especially when you are using a more procedural style of code, even when you use objects it will be useful, suggesting that you familiarize yourself with what you can read the PHP documentation on arrays .
The code I put in foreach
is only adding items to the array, for example, imagine that $pesquisa
is algo para pesquisar
.
// aqui dividimos a string "algo para pesquisar" em cada espaço
$v = explode(" ", $pesquisa);
// isto cria um array assim
// Array
// (
// [0] => algo
// [1] => para
// [2] => pesquisar
// )
// por cada palavra, adicionamos um item ao nosso array condicoes
$condicoes = [];
foreach ($v as $key => $value) {
$condicoes[] = "descricao LIKE '%{$value}%' OR grau LIKE '%{$value}%'";
}
// $condicoes, depois deste ciclo será
// Array
// (
// [0] => descricao LIKE '%algo%' OR grau LIKE '%algo%'
// [1] => descricao LIKE '%para%' OR grau LIKE '%para%'
// [2] => descricao LIKE '%pesquisar%' OR grau LIKE '%pesquisar%'
// )
We can use the implode () , which is the opposite of explode (), to transform $ conditions in a string, and we can even (should!) check for $ conditions (that is, if something was added to the array.)
$sql_condicoes = ""; // o SQL das condições é vazio caso não existam condicoes
if (count($condicoes) > 0) {
$sql_condicoes = " WHERE " . implode(" OR ", $condicoes);
}
$sql = "SELECT * FROM lentes" . $sql_condicoes;