PHP Error in MySQLi search engine

0

I recently managed to create a mysqli search engine in php. The problem is that if you find more than 1 result simply put the same user id and name.

if(!empty($_POST)){
if(isset($_POST["username"])){
   if($_POST["username"] !=""){
      include "conexion.php";
      $buscar = $_POST["username"];
      $sql1= "SELECT * FROM usuarios WHERE Username LIKE '%$buscar%'";
      $query = $con->query($sql1);
      if($row = mysqli_fetch_array($query)){
          echo "Resultados para: $buscar";
          do {
              ?>
              <br>
              <br>
              (ID: <?php echo $row['ID']; ?>) - <?php echo $row['Username']; ?>
              <?php
          }
          while (mysqli_fetch_array($query));    
        }
        else
        {
            echo "No se encontraron resultados para: $buscar";             
        }
    }
}

Suppose I enter "hello" and in the database there are 3 registered users with the name "hello" "hello1" "hello2", the code would give me this:

    Resultados para: hola 

(ID: 2) - hola 

(ID: 2) - hola 

(ID: 2) - hola

Instead of giving me something like this

(ID: 2) - hola 

(ID: 3) - hola1

(ID: 4) - hola2

I hope you can understand, thank you already.

    
asked by Gino Daloisio 16.05.2018 в 21:37
source

2 answers

0

Remember or keep in mind that the LIKE operator works in the following way:

  • LIKE '% string' will search for matches of the word at the end
  • LIKE 'string%' will search for matches of the word at the beginning
  • LIKE '% string%' will search for matches throughout the word
  •   

    Then since you're looking for that although the list of words   be hello hello1 hello2 , do not remove the number and show it to you like this.

    Then your query should be as follows

    $sql1= "SELECT * FROM usuarios WHERE Username LIKE '$buscar%'";
    

    I'll attach the small example I made

    select * from ejem where saludo LIKE 'ho%';
    +--------+
    | saludo |
    +--------+
    | hola1  |
    | hola2  |
    | hola3  |
    +--------+
    

    You can also do it in the following way and you will also get the expected result

    select * from ejem where saludo LIKE '%ho%';
    +--------+
    | saludo |
    +--------+
    | hola1  |
    | hola2  |
    | hola3  |
    +--------+
    
      

    The only operator that is not going to serve you for what you need is:

    select * from ejem where saludo LIKE '%ho';
    Empty set (0.00 sec)
    
        
    answered by 16.05.2018 в 21:47
    0

    As you can see, it is repeating the first record because you are not recovering the data well.

    When you make a query, the result is usually a kind of pointer placed in the first record. That pointer must be traversed, creating for example an array with the data that is in it and then you have to read that array.

    In your code you never pass the first record for that reason.

    Try doing it this way:

    #Creamos un array con el cual llenaremos cada fila
    $rows = array();
    $result = $con->query($sql1);
    
    while ($row = $result->fetch_array())
    {
        #Aquí dentro del bucle, se recorren los resultados y se agregan a $rows
        $rows[] = $row;
    }
    
    #Nuestra variable utilitaria, para escribir código limpio y legible
    $strHTML="";
    
    #Si no se encontraron datos, $rows será false y entrará en el else
    if ($rows){ 
        #Concatenamos esto a nuestra variable utilitaria fuera del bucle for
        $strHTML.= "Resultados para: $buscar";
        foreach ($rows as $row){
            #Seguimos concatenando
            $strHTML.="(ID: ".$row['ID']."-".$row['Username'].")".PHP_EOL;            
        }
    
    }else{
    
        $strHTML="No se encontraron resultados para: $buscar";      
    }
    #Imprimimos la información que se ha ido recogiendo
    echo $strHTML;
    

    I have corrected some things, such as the mixture of programming styles with respect to mysqli, using only the object-oriented style.

    Also, I have given more clarity to the code, using a single variable that concatenates the results and prints them at the end.

    I hope it serves you.

        
    answered by 16.05.2018 в 22:17