【问题标题】:Get multiple rows from phpmyadmin to Java using JSON使用 JSON 从 phpmyadmin 获取多行到 Java
【发布时间】:2016-03-04 23:45:14
【问题描述】:

大家晚上好,直到几天前我还从未使用过 PHP 或 JSON,而且我发现使用 JSON 从 phpmyadmin 到 Java 获取多行时遇到了麻烦。我已经编写了下面的代码,但是这只得到了最后一行。

我看了这篇帖子 (how to encode multiple rows from mysql into json using php) 并尝试了一下,但没有运气..

    <?php

    $user = 'root';
    $pass = '';
    $db = 'uopuser';

    $con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');


    $statement = mysqli_prepare($con, 'SELECT * FROM society');
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $society_id, $name, $email, $description);

    $society = array();

    while(mysqli_stmt_fetch($statement)){
        $society['society_id'] = $society_id;
        $society['name'] = $name;
        $society['email'] = $email;
        $society['description'] = $description;
    }

    echo json_encode($society);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

提前谢谢你!

【问题讨论】:

  • 问:“Java”从何而来?您的 PHP 1)在服务器上执行,2)服务器与数据库对话,3)您的“回声”可能会向浏览器写入一些有效的 JSON。问:您在哪里/如何使用“Java”???? PS:您的“while”循环是错误的 - 每次迭代都会覆盖以前的值。您可能想在循环内移动“回声”...
  • @paulsm4 我将使用这些数据为 Android 应用程序填充 ListView。目前我只需要让我的 PHP/JSON 正确。我会测试你的建议,谢谢你指出来。
  • 我怎么没看到这个!非常感谢你们。

标签: php json


【解决方案1】:

只需要将我的 echo 放入 while 循环中

while(mysqli_stmt_fetch($statement)){
            $society['society_id'] = $society_id;
            $society['name'] = $name;
            $society['email'] = $email;
            $society['description'] = $description;
        }

        echo json_encode($society);

while(mysqli_stmt_fetch($statement)){
        $society['society_id'] = $society_id;
        $society['name'] = $name;
        $society['email'] = $email;
        $society['description'] = $description;
        echo json_encode($society);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-26
    • 2015-07-11
    • 2022-01-15
    • 2015-01-19
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多