JSON只有一行正在打印
问题描述:
目前,我正准备将AJAX响应提供给客户端。在这种情况下(示例),我在数据库中有两个值为tuper
的值,但使用此代码时,它仅打印1 tuper
值行。JSON只有一行正在打印
下面是代码:
<?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);
?>
答
删除return
while循环中。首先创建数组,然后将其返回。
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
}
你在'while'循环中返回*,这意味着它永远不会循环多次。 – 2015-03-03 02:53:49