简体   繁体   中英

Empty array in response PHP/JSON

I'm coding a php server sending arrays response using JSON. Now i simply testing the php code but the result is empty:

{"routes":[]}

There is my code in 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);
}
?>

I'am testing in postman, sending POST:

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

1) Add

error_reporting(E_ALL); 

to the top of the script. If there is anything funny it will show the errors.

2) Change the post to a get for testing purposes 3) Go to the page

 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) Do we see anything and what? 5) If there is nothing use variables to test things

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

Add 2 lines to the final result and see the result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM