Terrance Shaw
Terrance Shaw

Reputation: 161

Invalid json_encode output

Starting a new project, and I've come upon a hitch moving from deprecated mysql_query commands to the new mysqli type arguments.

The code is as follows:

<?php

$mysqli = new mysqli("hostname", "username", "password", "dbname");

// Check the connection

if (mysqli_connect_errno()) {
    printf("Connect failed.");
    exit();
}

$sql = $mysqli->query("SELECT * FROM SafariFinder_Directory");

while ($rows = $sql->fetch_assoc()) {
    echo json_encode($rows);
}

echo $res;

$mysqli->close();

?>

This gets me the following output:

{"id":"3","inGameName":"Syrinathos","friendCode":"0000 0000 0000","safariType":"Normal","safariSlot1":"Aipom","safariSlot2":"Kecleon","safariSlot3":""}
{"id":"2","inGameName":"Herschel","friendCode":"1234 12341 234","safariType":"Zombie","safariSlot1":"Crawler","safariSlot2":"Runner","safariSlot3":""}
{"id":"4","inGameName":"Syrinathos","friendCode":"0000 0000 0000","safariType":"Normal","safariSlot1":"Aipom","safariSlot2":"Kecleon","safariSlot3":"Ditto"}
{"id":"6","inGameName":"Kira","friendCode":"2345 2345 2345","safariType":"Ghost","safariSlot1":"Shuppet","safariSlot2":"Haunter","safariSlot3":"Gengar"}

The only components it's missing to be valid JSON are the square brackets and the commas between the actual entries. Any assistance would be greatly appreciated.

Upvotes: 0

Views: 73

Answers (1)

xdazz
xdazz

Reputation: 160853

You should put the result into an array, then encode the array.

$rows = array();
while ($row = $sql->fetch_assoc()) {
    $rows[] = $row;
}

echo json_encode($rows);

Upvotes: 4

Related Questions