如何将mysqli_fetch_assoc结果转换为json格式?

时间:2013-04-23 11:46:55

标签: php json

我正在尝试将查询结果转换为json格式,以便我可以在另一个文件中使用jquery来抓取它。我没有得到任何错误,但它没有被识别为json。

    $patientquery = mysqli_query($connect, "SELECT * FROM login WHERE assignedTo='$logID'");

    $numrows = mysqli_num_rows($patientquery);

    if($numrows > 0)
    {
        while($rows = mysqli_fetch_assoc($patientquery))
        {
            $dbloginID = $rows['loginID'];
            $dbname = $rows['name'];


            $result[] = array('patient'=>array('id' => $dbloginID, 'name' => $dbname));


        }
    }
    else
    {
        $result[] = 'No Patients yet';
    }

echo json_encode($result);

2 个答案:

答案 0 :(得分:1)

你应该在循环中声明$ result,像这样

$result = array();

答案 1 :(得分:1)

请试试这个:

$patientquery = mysqli_query($connect, "SELECT * FROM login WHERE assignedTo='$logID'");

$numrows = mysqli_num_rows($patientquery);

$result = array();

if($numrows > 0)
{
    while($rows = mysqli_fetch_assoc($patientquery))
    {
        $dbloginID = $rows['loginID'];
        $dbname = $rows['name'];

        $result['patient'][] = array('id' => $dbloginID, 'name' => $dbname);
    }
}
else
{
    $result[] = 'No Patients yet';
}

echo json_encode($result);
相关问题