空数组,用于响应PHP / JSON

时间:2019-04-06 17:22:06

标签: php json post

我正在编码一个使用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

2 个答案:

答案 0 :(得分:0)

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();

答案 1 :(得分:0)

在最终结果中添加2行,然后查看结果:

'routes' => $dbdata,
'valid' => $result != false,
'num_rows' => $result->num_rows,