What’s wrong with this search form?

Asked

Viewed 98 times

0

I created this search form, so it’s returning all blank!

Here the form:

<h3>O que você esta procurando? Digite aqui:</h3>
        <form class="form-inline" action="busca.php" method="post">
            <div class="form-group">
                <input type="text" class="form-control" id="palavra" placeholder="Digite aqui..." name="palavra">
            </div>
            <div class="form-group">
                <label for="cidade">Selecione a cidade:</label>
                <select name="cidade" class="form-control" id="cidade">
                    <option value="sao-gabriel-da-palha">São Gabriel da Palha</option>
                    <option value="sao-domingos-do-norte">São Domingos do Norte</option>
                    <option value="vila-valerio">Vila Valério</option>
                </select>
            </div>
            <button type="submit" class="btn btn-default" value="Buscar">Buscar</button>
        </form>

And here are the codes I used to connect and search in PHP:

<?php

  $hostdb = "localhost";
        $userdb = "root";
        $passdb = "root";
        $tabledb = "empresa";

        $conecta = mysqli_connect($hostdb, $userdb, $passdb) or die(mysqli_connect_error());
        @mysqli_connect($tabledb, $conecta) or die("Erro ao se conectar com o banco de dados");

        $busca = $_POST['palavra'];
        $cidade = $_POST ['cidade'];

        $busca_query = mysqli_query($conecta,"SELECT * FROM empresa WHERE nome LIKE '%$busca%' AND cidade = '$cidade'") or die(mysqli_error());

        if (empty($busca_query)){
            echo "Nenhum resultado para a sua busca.";
        }

        if ($busca_query){
            while ($dados = mysqli_fetch_array($busca_query)){
                echo "Nome: $dados[nome]</br>";
                echo "Endereço: $dados[endereco]</br>";
                echo "Cidade: $dados[cidade]</br>";
                echo "Telefone: $dados[telefone]</br>";
                echo "email: $dados[email]</br>";
                echo "<hr>";
}
        }else{
            echo "Nenhum resultado para a sua busca.";
        }


        ?>

Could someone explain to me why the query is returning blank?

  • You need to pass the connection as the first argument in mysqli_query() and in mysqli_error()

  • Give me an example of this, because I’m new, I’m still learning!

2 answers

5

The main error occurs because mysqli_query() expects exactly two arguments the first is always connection and the second the query.

Change:

 $busca_query = mysqli_query("SELECT * FROM empresa WHERE nome LIKE '%$busca%' AND cidade = '$cidade'") or die(mysqli_error());

To:

$busca_query = mysqli_query($conecta, "SELECT * FROM empresa WHERE nome LIKE '%$busca%' AND cidade = '$cidade'") or die(mysqli_error($conecta));

Other problems are the function mysqli_error() also asks the connection if it does not exist you cannot check the error while calling mysqli_connect() in this case of establishing the connection the correct is to call mysqli_connect_error() or mysqli_connect_errno().

You can delete the call from mysqli_select_db() passing as the name of the database as the fourth argument in mysqli_connect()

Change:

$conecta = mysqli_query($hostdb, $userdb, $passdb) or die(mysqli_error());

To:

$conecta = mysqli_connect($hostdb, $userdb, $passdb) or die(mysqli_connect_error());

Better structure the if, if the query return is false still the while block will be executed which will generate an error. Leave it like this:

if ($busca_query){
    while ($dados = mysqli_fetch_array($busca_query)){
        echo "Nome: $dados['nome']</br>";
        echo "Endereço: $dados['endereco']</br>";
        echo "Cidade: $dados['cidade']</br>";
        echo "Telefone: $dados['telefone']</br>";
        echo "email: $dados['email']</br>";
        echo "<hr>";         
    }
}else{  
    echo "Nenhum resultado para a sua busca.";
}   
  • It still keeps bringing the blank result! Does it have any other error??

  • @Wpfan tested the direct query in the database?

  • No, that way I didn’t test it. I made all the changes you recommended and keep returning blank, nor the message of any results found appears!

  • @Wpfan first you should call the mysqli_connect() only to call mysqli_query() see in the code you call mysqli_query() as if it were the mysqli_connect() => mysqli_query($hostdb, $userdb, $passdb)

  • Well, it has already started to get better, now at least the Error message is appearing when connecting to the database! And now, why are you making an error in connection?

  • @Wpfan can be N invalid user and password things etc, which was the error message?

  • He printed the error on this line here: @mysqli_connect($tabledb, $connects) or die("Error connecting to database");

  • @Wpfan you should not use @ in their code they hide the errors. vc have call the arguments in the right order, first the server address, database user, password and the database name (optional) equal to $conecta = mysqli_connect($hostdb, $userdb, $passdb)

  • I did the test and still giving Error while connecting to the database

  • @rray mysqli_connect() expects Parameter 2 to be string, Object Given in ... on line 9 line 9 mysqli_connect($tabledb, $connects) or die("Error connecting to database"); Without the @

  • Boy, how can something so simple to do is giving you such a headache

  • @Leocaracciolo my reply was on top of the first version (funny q n vi the other two) n has this call with two arguments.

  • @Wpfan the correct code looks like this: https://pastebin.com/GWXSWAzE

  • in the code there are 2 lines $connects = mysqli_connect.. @mysqli_connect($ta ....

  • @Leocaracciolo in this last edition has this line but it is wrong and also not necessary since the first one does it in the right way. I do not know if the explanation with the correction were confused or confused in the answer, I set up this link https://pastebin.com/GWXSWAzE with the right code. The answer basically says modify three dots, (connect(), query() and if).

  • @Wpfan error appears? the name of the bank is company itself/?

  • I’m sorry the name of the bank is Guianortecapixaba, I changed and continues the same thing

  • @Wpfan is not possible, I tested the code of rray and is running well see here with its code http://kithomepage.com/sos/Product.php

  • now I can give +1, running round what is in Pastebin!

Show 14 more comments

0

Well for me to get it done and to make it work, it had to be this way here, I thank you for all your help:

<?php
        $servidor = "localhost";
        $usuario = "root";
        $senha = "root";
        $tabela = "guianortecapixaba";

        $conexao = new mysqli($servidor, $usuario, $senha, $tabela);

        if ($conexao->connect_error) {
            die("Erro: " . $conexao->connect_error);
        }

        $busca = $_POST['palavra'];
        $cidade = $_POST ['cidade'];

        $sql = "SELECT * FROM empresa WHERE nome LIKE '%$busca%' AND cidade = '$cidade'";
        $resultados = $conexao->query($sql);

        if ($resultados->num_rows > 0) {
            while($linha = mysqli_fetch_array($resultados)) {
                print("Nome: " . $linha['nome'] . "</br>");
                print ("Endereço:". $linha['endereco']."</br>");
               // print ("Cidade:". $linha['cidade']."</br>");
                print ("Telefone:". $linha['telefone']."</br>");
                echo "email:". $linha['email']."</br>";
                echo "<hr>";
            }
        } else {
            echo "Nenhum resultado para a sua busca.";
        }

        $conexao->close();

Browser other questions tagged

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