Your query is not a valid query, so the return of mysqli_query
is a BOOLEAN
, in this case false
.
You have other code problems. You close the loop here foreach ($v as $key => $value);
, instead of adding more conditions in the query 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 it’s one of the most useful data structures in the language, especially when you’re using a more procedural code style, even when you use objects it’s useful, I would suggest getting familiar with what’s possible by reading PHP documentation about arrays.
The code I put on foreach
just 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 turn $conditions into a string, and even we can (must! ) check for $conditions (ie if something has been 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;
Take out that last
OR
than the syntax error.– rray
Places code as text and not as image.
– Leite
If you change your question a little, this example may be useful for other users searching for this.
– Leite