简体   繁体   中英

json_encode is returning boolean values instead of json string

Very simple: I am using a prepared statement to select data and return it in a json_encode form.

The problem: Instead of receiving a JSON string full of the returned data, I am getting something like this:

[true, true, true, true]

My guess is that it is checking whether every value is set and then it is just returning whether the value is set or not, in a boolean form.

$stmt = $connection->prepare("SELECT * FROM details WHERE age = ?");
$stmt->bind_param('i', $age);
$stmt->execute();
$json = array();
while($row = $stmt->fetch()){
$json[] = $row;
}

echo json_encode($json);

This is the AJAX that I am using.

$(document).ready(
    function () {
        $('#call_back_btn').click(function() {
            $.post("process.php", {
                name:   $('#name').val(),
                age:    $('#age').val(),
                value:  $('#value').val(),
                task:   "submit_prepared"
            }, 
            function(data) {
                alert(data);
            })
        })
    });

What should I do so that my data is returned into a JSON string? Thank you.

Please have a look at the documentation for $stmt->fetch() . It is completely correct that you receive booleans. Modified the code to use bind_result .

$stmt = $connection->prepare("SELECT name, age FROM details");
$stmt->execute();
$stmt->bind_result($name, $age);
$json = array();
while($stmt->fetch()){
  $json[] = array("name" => $name, "age" => $age);
}

echo json_encode($json);

Try to print the $json from the php just to make sure that the array is correct. Then print the json_encode($json) variable in php again, without ajax. I generally hard code the query and run it from the browser directly. This way you will make sure that the correct data is being generated by php.

Also try using the $.ajax function. This way you will have more control.

$.ajax({
    url: 'process.php',
    type: 'POST',
    dataType: 'JSON',
    data: {YOUR DATA GOES HERE},
    success: function(data){
            alert(data);
     }
});

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