首页 > 解决方案 > 响应 PHP/JSON 的空数组

问题描述

我正在编写一个使用 JSON 发送数组响应的 php 服务器。现在我只是测试 php 代码,但结果是空的:

{"routes":[]}

PHP中有我的代码:

<?php

require_once 'connect.php';

if ($_SERVER['REQUEST_METHOD'] =='POST') {

    $region = $_POST['region'];

    $sql = "SELECT * FROM routes WHERE region='$region'";

    $result = mysqli_query($conn, $sql);

    $dbdata = array();

    while ($row = $result->fetch_assoc()) {
        $dbdata[] = $row;
    }

    $obj = (object)[

        'routes' => $dbdata
    ];

    echo json_encode($obj, JSON_UNESCAPED_SLASHES);
}
?>

我正在邮递员中进行测试,发送 POST:

http://MY PATH/filter.php?"region"=West

标签: phpjsonpost

解决方案


1) 添加

error_reporting(E_ALL); 

到脚本的顶部。如果有什么有趣的地方,它会显示错误。

2) 将帖子更改为获取以进行测试 3) 转到页面

 http://MY PATH/filter.php?"region"=West //-> remove the quotes
 http://MY PATH/filter.php?region=West //->This is what the request will look like

4)我们看到了什么吗?5)如果没有什么使用变量来测试东西

 ex: 
     $region = $_GET['region'];

echo $region; //Should print West

$sql = "SELECT * FROM routes WHERE region='$region'";

$result = mysqli_query($conn, $sql);
echo "<pre>";
print_r($results) // and so on until you see something you can use
$dbdata = array();

推荐阅读