简体   繁体   English

json_encode与MySQL数组

[英]json_encode with MySQL array

I'm getting an array with values out of my MySQL and I'm trying to json_encode() it. 我正在从MySQL中获取一个带有值的数组,并尝试对其进行json_encode()。 Theres no output though, nothing. 虽然没有输出,但是什么也没有。 Just a white screen, no error, nothing. 只是一个白色的屏幕,没有错误,什么都没有。 Any ideas? 有任何想法吗? The array $rows is perfectly filled with values. $ rows数组完美地填充了值。

if (!$connection = mysqli_connect($db_host, $db_user, $db_pw, $db))
    die( "Connection not successful.\n" );

$sql_qry = "SELECT * FROM `table`;";
if (!$result = mysqli_query($connection, $sql_qry))
    echo "Wasn't able to send query: ".mysqli_error($connection)."\n";

while ($rows[] = mysqli_fetch_assoc($result));

mysqli_close($connection);

echo json_encode($rows);

Your while assignment isn't actually iterating the resultset and assigning the existing rows from your SQL Query to this variable. while分配实际上并没有迭代结果集并将SQL查询中的现有行分配给此变量。 If you wish to access the entire contents of the returned resultset outside of the scope of your while statement, then you need to walk the resultset and assign each row to an array defined before your while statement's execution: 如果希望访问while语句范围之外的返回结果集的全部内容,则需要遍历结果集并将每一行分配给执行while语句之前定义的数组:

$rows = array();
while ($ret = mysqli_fetch_assoc($result)):
    $rows[] = $ret;
endwhile;

mysqli_close($connection);

echo json_encode($rows);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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