Pulling Data from Database → Some help needed in understanding

<?php 
include 'dbConnection.php';

$sql = "SELECT * FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
	$data = array();
	while ($row = $result->fetch_assoc()) {
		$data[] = $row;
	}
}


// Returning JSON Format
echo json_encode($data);

I understand the while loop very well, but I am facing certain difficulty in understanding one part of a code →


$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
  1. How is this part operating → $row = $result->fetch_assoc())
  2. What about this part → $data[] = $row;

How should I debug what is going in the causality of logical flow?

w/o echo how come data is published on a PHP page.

or echoing json_encode can also publish the data.

Is it possible that you updated the local file, but somehow missed out on uploading the updated file to the site?

1 Like

Let me check This, but chances are low because I am using sublime SFTP and I have binded key Ctr+s to server upload so the moment I save them I also automatically upload them to the server.

Bit off-topic but you don’t need the loop at all:

$data = $result->fetch_all();

https://www.php.net/manual/en/mysqli-result.fetch-all.php

Its not offtopic any insight is helpful for learners like me. Thanks.

Also be careful with that echo. If there were no rows retrieved, $data doesnt exist, and json_encode($data) will fail because you’re using $data without definition.

1 Like

Noted, Thanks.

I’d write it like this:

$sql = "SELECT * FROM students";
$result = $conn->query($sql);

// Until proven otherwise, we will assume there are no students
// This makes sure $students is always defined, even when there are no students in the database
$students = [];

// This while loop fetches rows from the database one by one.
// When there are no more records in the database then $result->fetch_assoc()
// returns false, and since an assignment evaluates to the right hand
// side of the assignment the while loop will stop
while ($row = $result->fetch_assoc()) {
    // Add the row from the database to our students
    $data[] = $row;
}

// Echo'ing JSON Format
echo json_encode($data);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.