0

I am trying to convert my PHP array that i get as a query result to a JSON array. But look like it does not work. Any help would be appriciated.

        $stmt = $db->prepare("SELECT * FROM companies WHERE companyID = ?");

        if($stmt == "false"){
            die('Query error !'.$db->error);  
        }
        $stmt->bind_param('i', $companyID);
        $stmt->execute();
        $result = $stmt -> get_result();
        $companies = $result ->fetch_all(MYSQLI_BOTH);

        echo json_encode(array('companies' => $companies));
5
  • 1
    How does it not work? What is the result of your current code? What do you expect it to look like? Commented Sep 30, 2014 at 19:30
  • I expect a JSON array but there is no JSON array Commented Sep 30, 2014 at 19:32
  • But look like it does not work. please be even less specific if possible Commented Sep 30, 2014 at 19:32
  • Does $result ->fetch_all actually give you an array or just something array-like? Commented Sep 30, 2014 at 19:33
  • 1
    What is the result of echo json_encode(array('companies' => $companies));? Commented Sep 30, 2014 at 19:33

1 Answer 1

4

It looks like what you're experiencing is JSON itself. There is an existing, excellent answer here that will explain that. The summary is that an array with string keys in PHP is an object in JSON, since arrays can only have numeric indexes.

I hope this answers your question directly enough, and I think it will change how you think of the relationship between PHP and JSON.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.