Ahsan Imtiaz Ahsan Imtiaz - 2 months ago 9
MySQL Question

echo query return data from array

This is the php code that I wrote to retrieve data from my database, When i am trying to echo the required data nothing is displayed, if I

json_encode
result and echo it, then I can see that there is data in side the array.

<?php
require_once('connection.php');
$retval = $connect->query("SELECT user_name FROM users");
$result = array();
while ($record = $retval->fetch_array(MYSQLI_ASSOC)) {
$result[] = $record;
echo $result['user_name'];
}
?>

Answer

Note that, if you want to print user_name inside the while loop than no need to store in another array.

You can just use like:

<?php
while ($record = $retval->fetch_array(MYSQLI_ASSOC)) {
  echo $record['user_name']; // will print all user_name
}
?>

If you want to use $result somewhere else, as you are talking about the json_encode() than you can store it in $result array.

<?php
while ($record = $retval->fetch_array(MYSQLI_ASSOC)) {
  echo $record['user_name']; // will print all user_name
  $result[] = $record;    // will store all username in result array
}
?>

From your question: if I json_encode result and echo it, then I can see that there is data in side the array. Yes json_encode() will work because you are using array.