PHPJSON生成问题

PHP JSON generation problems

下面的代码应该发回 json 数据库中的信息。

需要两个参数grade和subject。问题是,当我使用的参数不在数据库中时,一切都按预期工作,没有条目,但是如果它从数据库中得到答案,什么也没有出现。我真的没什么意思。我需要的值在那里我试过了,没有错误记录到日志文件中。作为服务器在 Debian 上运行带有 php5.6.22 的 apache2。我不知道我做错了什么。希望有人能帮助我。

代码:

case 'get_books':
    $grade = $_GET['grade'];
    $subject = $_GET['subject'];

    $sqlt = "SELECT * FROM book_type WHERE subject=".$subject." AND grade=".$grade;
    $sql = mysqli_query($db, $sqlt);
    if(!$sql){
        print(json_encode(array('response' => 2)));
        die();
    }

    $response = array();
    $response['books'] = array();
    while($row=mysqli_fetch_assoc($sql)) {
        $book = array();

        $book['fullname'] = $row ["fullname"];
        $book['ISBN'] = $row ["ISBN"];
        $book['id'] = $row ["id"];

        array_push($response['books'], $book);
    }
    $response['response'] = "1";
    print(json_encode($response));
    die();

我想这可能是你的问题:

array_push($response['books'], $book);

据我所知,您不能将变量推送到数组的特定索引中,因为没有为被推送的项目提供键。

最好是这样:

case 'get_books':
$grade = $_GET['grade'];
$subject = $_GET['subject'];

$sqlt = "SELECT * FROM book_type WHERE subject=".mysqli_real_escape_string((htmlspecialchars_decode($subject, ENT_QUOTES)))." AND grade=".mysqli_real_escape_string((htmlspecialchars_decode($grade, ENT_QUOTES)));
$sql = mysqli_query($db, $sqlt);
if(!$sql){
    print(json_encode(array('response' => 2)));
    die('sql failed');
}

$response = array();
$response['books'] = array();
$response['validator'] = 'valid';
$i = 0;
while($row=mysqli_fetch_assoc($sql)) {
    $book = array();
    $book['fullname'] = $row["fullname"];
    $book['ISBN'] = $row["ISBN"];
    $book['id'] = $row["id"];
    $response['books'][$i] = $book;
    $i++;
}
$response['response'] = "1";
var_dump($response);
//echo json_encode($response);
die();