Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!