如何将 Mysql/php 数组格式化为 json?

发布于 2024-11-05 15:21:42 字数 382 浏览 0 评论 0原文

之前问过这个问题,但我已将问题范围缩小到这段代码。这是我的代码,当我运行它时,它只是说“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);

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

去了角落 2024-11-12 15:21:42

首先,您已将 echo 放在循环之外,该循环仅回显最后一项而不是所有人,并且您不会检查查询是否有错误。

相反,这就足够了:

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

它将结果放入一个 assoc 数组中,然后将整个数组转换为 json 并打印它。

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.

黎夕旧梦 2024-11-12 15:21:42

您可能遇到的问题是在您的赋值语句中:

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

您应该将其更改为以下内容:

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文