1

I have used the code below to extract the data from my database and convert it into an array. My problem is that the echo json_encode function does not work and when running this code (without the print_r function) I am left with a blank page.

$query = "SELECT * From table";

$resultarray = array();

if ($result = mysqli_query($connection, $query)) {

     while ($row = mysqli_fetch_row($result)) {

         $resultarray[] = $row;    
     }

     print_r($resultarray); // This line shows that the array is works but the code below does not convert to JSON.

     echo json_encode($resultarray);
}

I have used the print_r function to make sure that I have created an array within my code. I have gone around in circles for hours and I do not understand what I am doing wrong. If I use the print_r function and view the page source I get the following:

 Array
(
[0] => Array
    (
        [0] => 5
        [1] => Name 1
        [2] => Description 1
        [3] => Location 1

    )

[1] => Array
    (
        [0] => 6
        [1] => Name 2
        [2] => Description 2
        [3] => Location 2

    )

[2] => Array
    (
        [0] => 45
        [1] => Name 3
        [2] => Description 3
        [3] => Location 3

    )

Thanks.

Brett
  • 11
  • 1
  • 4

3 Answers3

0

You forgot to add double quotation on this line:

$query = "SELECT * From table;

and because of that internal server error has occurred.

first line code should be like this

$query = "SELECT * From table";

Nikhil Vaghela
  • 2,088
  • 2
  • 15
  • 30
  • Good spot, but that is not the issue. I edited the $query when pasting it in stack overflow to make the code clearer but missed the ending ". The code that I am running has this and it query is executed in the database. I'm having issues converting my array into JSON. – Brett May 16 '16 at 11:56
  • Please check above answer – user6123296 May 16 '16 at 12:20
0
$con = mysqli_connect("localhost", "username", "password", "dbname");
if (mysqli_connect_errno()) {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql ="SELECT * FROM `table_name`";
if ($result = mysqli_query($con, $sql)) {
    while ($row = mysqli_fetch_row($result)) {
       $resultarray[] = $row;
    }
    echo json_encode($resultarray);
}
mysqli_close($con);
0

$conn = mysqli_connect("localhost", "root", "root","db_rest");
$query = "SELECT * From users";
$resultarray = array();
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_row($result)) {
$resultarray[] = $row;
}
echo json_encode($resultarray);
}