Fabian S. Fabian S. - 5 months ago 21
HTML Question

PHP JSON generation problems

The code below should send back an json with informations in a Database.

It takes two parameters grade and subject. The problem ist, when I use parameters are not in the database behind everything works as expected no entry, but if it would get an answer from the database nothing appears. I mean really nothing. The values i need are there i tried this and no errors are logged into the logging file. As server runs apache2 with php5.6.22 on Debian. I don't know what i did wrong. Hopefully someone can help me.

The Code:

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

Jay Jay
Answer

I think this might be your problem:

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

as far as I know you can't push a variable into a specific index of an array since no key is provided for the item being pushed.

It would be better to do this as follows:

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