willy henderson
willy henderson

Reputation: 19

How to format a Mysql/php array for json?

Asked this before, but I've narrowed down the issue to this bit of code. Here's my code, when I run it, it just says "null"..

$getmsg = "SELECT * FROM user WHERE account_id = $id";      
$showmsg = @mysqli_query ($dbc, $getmsg);
        while ($row = mysqli_fetch_array($showmsg, MYSQLI_ASSOC)) {

$arrResults = array($row['user_username']);


} // END WHILE


// Print them out, one per line
echo json_encode($arrResults);

Upvotes: 0

Views: 1252

Answers (2)

A Jolly Geek
A Jolly Geek

Reputation: 262

The problem you are likely having is in your assignment statement:

$arrResults = array($row['user_username']);

You should change it to the following:

$arrResults[] = $row['user_username'];

Upvotes: 1

rzetterberg
rzetterberg

Reputation: 10268

First of all you have put the echo outside the loop which just echoes the last item instead of everyone and you don't check if there is a error with your query.

Instead this would be sufficient:

$getmsg = "SELECT * FROM user WHERE account_id = $id";      
$result = @mysqli_query($dbc, $getmsg) or die("Error: " . mysql_error());
$result = mysql_fetch_assoc($result);
echo json_encode($result);

It puts the result in one assoc array and then converts the whole array to json and prints it.

Upvotes: 4

Related Questions