JSON只打印一行

时间:2015-03-03 02:42:35

标签: php mysql arrays json

目前我正准备一份AJAX响应,将其发送给客户。在这种情况下(示例),我的数据库中有两个tuper值行,但使用此代码时,它只打印1 tuper个值行。

以下是代码:

<?php
  $con=mysqli_connect("localhost","root","","project");

  $user = isset($_POST['user']) ? $_POST['user'] : '';
  $pass = isset($_POST['pass']) ? $_POST['pass'] : '';


  function account($user, $pass)
  {
    global $con;
    $result=mysqli_query($con,"SELECT * FROM account WHERE   username='$user'");
     while($row=mysqli_fetch_array($result))
     {
        $x = array('Username'=> $row['username'],
                    'Password' => $row['password']);

        $accounts['Accounts'][]= $x;
        return json_encode($accounts);
    }

 }
 echo $acountList = account("tuper",$pass);

?>

1 个答案:

答案 0 :(得分:3)

删除while循环中的return。首先创建数组,完成后再返回它。

function account($user, $pass)
{
    global $con;
    $data = array(); // setup container
    $result = mysqli_query($con,"SELECT * FROM account WHERE username='$user'");
    while($row=mysqli_fetch_array($result)) {
        $x = array(
            'Username'=> $row['username'],
            'Password' => $row['password']
        );

        $data[] = $x; // push inside the container
    }

    $accounts['Accounts'] = $data; // after the loop is done
    return json_encode($accounts); // then return it
}