Query the database using ORDER BY kills my search

Asked

Viewed 34 times

1

My code displays a list of people and a search field at the top. everything works normal, including the search. But I need people to show up at random. The problem is that when I use ORDER BY Rand() (or any other ORDER BY) my search stops working. when searching appears the error assigned to $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');
}
?>
  • 'Failed connection to bank' - assigned to ! $result

1 answer

2


A syntax representative of the SELECT declaration is the following::

 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. SELECT’s full syntax includes additional clauses. All clauses that follow the list of columns to be displayed 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() ";
}
  • works. thank you very much. now I need to understand why it works like this and not in my way. back to studies! thank you!

  • @Tomzé, I edited the answer explaining this. If you solved your problem mark the answer as accepted, see https://i.stack.Imgur.com/evLUR.png.

  • perfect. now it’s clear. once again thank you for your attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.