Querying database using ORDER BY kills my search

1

My code displays a list of people and a search field at the top. everything works fine, including searching. but I need people to appear randomly. The problem is that when I use the ORDER BY rand () (or any other ORDER BY) my search stops working. when doing the search appears the error attributed to the $ result.

<?php require_once("conecta.php"); ?>

<?php
//consulta dos dados

$assistentes = "SELECT * FROM assistentes ORDER BY rand() ";


if(isset($_GET["buscauser"])){
    $nomebusca = $_GET["buscauser"];
    $assistentes .= " WHERE nome LIKE '%{$nomebusca}%' OR sobrenome LIKE '%{$nomebusca}%' OR cidade LIKE '%{$nomebusca}%'  ";
}

$resultado = mysqli_query($conecta, $assistentes);
if (!$resultado){
    die('Falha na conexao com o banco');
}
?>
    
asked by anonymous 09.06.2018 / 06:11

1 answer

2

A representative syntax of the SELECT statement is as follows:

 SELECT valores_a_exibir
     FROM nome_da_tabela
     WHERE expressão
     GROUP BY como_agrupar
     HAVING expressão
     ORDER BY como_ordenar
     LIMIT contagem_de_linhas;

This syntax is simplified. The complete SELECT syntax includes additional clauses. All clauses that follow the list of columns to display are optional.

For example, you do not need to include a LIMIT clause when writing a SELECT statement. However, any clauses you include must be specified in the order shown .

if(isset($_GET["buscauser"])){
    $nomebusca = $_GET["buscauser"];
    $assistentes = "SELECT * FROM assistentes WHERE nome LIKE '%{$nomebusca}%' OR sobrenome LIKE '%{$nomebusca}%' OR cidade LIKE '%{$nomebusca}%' ORDER BY rand()";
}else{
    $assistentes = "SELECT * FROM assistentes ORDER BY rand() ";
}
    
09.06.2018 / 07:35