Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda