0

I am unable to get this right! I am simply trying to create an array of names $json from mysql table data and later return this data as json using this code:

json_encode($json)

Getting syntax error in the 5th line in the following code where the $json array is assigned values from the database inside the loop.

$sql = "select * from mytable";
$result = $mysqli->query($sql);
$json = array();
while($row = $result->fetch_assoc()){
     $json[] = ['id'=>$row['id'], 'text'=>$row['title']];
}

I tried replacing the single quotes with double quotes.. but no success..

having a bad day :-(

7
  • 1
    did you try to execute your code or is that syntax error just from your IDE? Commented Aug 22, 2017 at 21:01
  • just from the ide... Commented Aug 22, 2017 at 21:01
  • then refer to the answer below bt AbraCadaver, it will fix your issue, although your code as it appears right now is also correct and will execute. It is just your IDE which picks this up as a syntax error. Commented Aug 22, 2017 at 21:02
  • 1
    What PHP version are you using? Commented Aug 22, 2017 at 21:06
  • 1
    So it's just the IDE. See if there is an update for it or way to have it recognize newer PHP syntax. Commented Aug 22, 2017 at 21:17

1 Answer 1

3

Most likely the [] syntax, you need to use array() instead for PHP < 5.4.0:

$json[] = array('id'=>$row['id'], 'text'=>$row['title']);

But it could be much easier if you change the query to select only the columns needed AS the name needed and use fetch_all():

$sql = "select id, title AS text from mytable";
$result = $mysqli->query($sql);    
$json = $result->fetch_all(MYSQLI_ASSOC);

If it's just the IDE, see if there is an update for it or way to have it recognize newer PHP syntax.

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

1 Comment

Good answer. Still adds value even if the array syntax was not root cause. (though suppose it was even if false err from IDE?).

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.