Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
How to echo and retrive multiple rows with php

First off all hello to you all. The problem is I am making an ajax call from javascript to php file. And in that php file there is a prepared statement which returns 15 rows. I need to json_encode() these rows and send back to the javascript file so that I can use all of these information in each row which are info about users' profile. What's wrong with my code? I call fetch_assoc() constantly until all of the rows are processed yet when I display it on the console it only shows one row.

This is get_info.php:

 // Get the profile info
    $stmt = $conn->prepare("SELECT teachers.fname, teachers.lname, profile.img_url, profile.gender, profile.introduction, profile.city, profile.preference, profile.keyword FROM profile INNER JOIN teachers ON profile.user_id = teachers.id WHERE profile.keyword=? ORDER BY RAND() LIMIT 15");
    $stmt->bind_param("s", $keyword);
    $stmt->execute();
    $result = $stmt->get_result(); // get the mysqli result
    $resultArray = [];
    if ($result->num_rows > 0) 
    {
        while ($row = $result->fetch_assoc()) 
        {   
            $resultArray = $row;    
        }
        $result = json_encode($resultArray);
        echo $result;
    }

And this is the javascript file where the ajax request is:

$(document).ready(function() 
{
  $.getJSON("get_info.php", function(result)
  {
    console.log(result);
  }
)})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You keep overwriting $resultArray every time you loop, so you'll only ever see the last row returned by the query.

You need to make assign $row to a new element of $resultArray each time you loop - then adds rows to the array, instead of overwriting the variable with a single row.

It's very simple to do that:

$resultArray[] = $row;  

You may also want to read https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying to refresh your memory of this key bit of PHP syntax.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda