简体   繁体   中英

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);

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.

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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM