【问题标题】:PHP JSON generation problemsPHP JSON 生成问题
【发布时间】:2016-10-23 02:56:35
【问题描述】:

下面的代码应该返回一个包含数据库中信息的 json。

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

代码:

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

【问题讨论】:

  • 您是否开启了显示错误或检查您的错误日志?
  • 现在错误已记录到日志文件中——如果我们知道这些错误是什么,将会有所帮助。
  • 打错了...我的意思是没有
  • 试过回声?可能设置标题?
  • 是的,我想尽了一切办法

标签: php html arrays json php-5.6


【解决方案1】:

我认为这可能是你的问题:

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

【讨论】:

  • 这会返回:警告:array_push() 期望参数 1 是数组,在 /var/www/html/test/api/app.php 第 58 行给出的 null
  • @FabianS。我的解决方案中没有使用 array_push(),那么你是怎么得到这个错误的?
  • 我修好了,但问题是一样的,没有打印出来
  • @FabianS。 /var/www/html/test/api/app.php 的第 58 行是什么?
  • 我忘了评论之前的array_push
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 2013-06-03
  • 2014-08-29
  • 2019-08-21
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
相关资源
最近更新 更多