0

I want to select all the recipes in my food database and encode them into a simple JSON response. I've looked at solutions around stack overflow and have implemented a sensible looking script.

No JSON array is returned / echoed.

Could someone tell me where I'm going wrong?

<?php
$type = "recipe";
$conn = mysqli_connect("localhost", "root", "", "food"); // SAMPLE CREDENTIALS
$sql = "SELECT * FROM wp_posts WHERE post_type = '$type' ";
$query = mysqli_query($conn, $sql);

$i = 0; // INCREMENT
$arr = [];

if($query) {
    while($row = mysqli_fetch_assoc($query)) {
        $jsonArrayObject = (array('title' => $row['post_title'] , 'excerpt' => $row['post_content']));
        $arr[$i] = $jsonArrayObject;
        $i++;
    }
    $json_array = json_encode($arr, JSON_PRETTY_PRINT);
    echo $json_array;
}
else {
    echo "Error in database";
}
?>

ARR VARIABLE PRINT OUT enter image description here

7
  • what is the output of $arr? Commented Jan 26, 2016 at 11:37
  • I can't see the error but php isn't a language I know well. However standard debugging should solve this quite quickly... add an echo inside the loop for each jsonArrayObject. The results should point you straight at the problem (or at least give you more information for the question here) Commented Jan 26, 2016 at 11:39
  • @PathikVejani It prints out the array object perfectly. Commented Jan 26, 2016 at 11:43
  • you should echo $arr; and show us the output... Commented Jan 26, 2016 at 11:43
  • @pritesh I have added a screenshot of the print out of the $arr variable. Commented Jan 26, 2016 at 11:45

1 Answer 1

1

Check if your PHP version is 5.4.0 or above.

The option JSON_PRETTY_PRINT was introduced in that version according to http://php.net/manual/en/json.constants.php

If your PHP version is below 5.4.0 leave the option.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.