使用PHP将SQL查询中的项目数组转换为JSON


Converting an array of items from SQL query into JSON using PHP

我使用下面的代码从数据库中提取数据并将其转换为数组。我的问题是echo json_encode函数不起作用,当运行此代码(没有print_r函数)时,我只剩下一个空白页。

$query = "SELECT * From table";
$resultarray = array();
if ($result = mysqli_query($connection, $query)) {
     while ($row = mysqli_fetch_row($result)) {
         $resultarray[] = $row;    
     }
     print_r($resultarray); // This line shows that the array is works but the code below does not convert to JSON.
     echo json_encode($resultarray);
}

我使用了print_r函数来确保在代码中创建了一个数组。我已经绕了好几个小时了,我不明白自己做错了什么。如果我使用print_r函数并查看页面源,我会得到以下内容:

 Array
(
[0] => Array
    (
        [0] => 5
        [1] => Name 1
        [2] => Description 1
        [3] => Location 1
    )
[1] => Array
    (
        [0] => 6
        [1] => Name 2
        [2] => Description 2
        [3] => Location 2
    )
[2] => Array
    (
        [0] => 45
        [1] => Name 3
        [2] => Description 3
        [3] => Location 3
    )

谢谢。

$con = mysqli_connect("localhost", "username", "password", "dbname");
if (mysqli_connect_errno()) {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql ="SELECT * FROM `table_name`";
if ($result = mysqli_query($con, $sql)) {
    while ($row = mysqli_fetch_row($result)) {
       $resultarray[] = $row;
    }
    echo json_encode($resultarray);
}
mysqli_close($con);

$conn=mysqli_connect("localhost"、"root"、"根"、"db_rest")
$query="SELECT*来自用户"
$resultarray=array()
if($result=mysqli_query($conn,$query)){
while($row=mysqli_fetch_row($result)){
$resultarray[]=$row
}
echo json_encode($resultarray)
}

您忘记在这行添加双引号:

$query = "SELECT * From table;

并且因为发生了内部服务器错误。

第一行代码应该像这个

$query = "SELECT * From table";