Home > Back-end >  How do I use json_encode?
How do I use json_encode?

Time:10-03

So I have this autocomplete form, which basically searches for your school.

var school = ["School1","School2"]; /* JS, wanted output */

And I have this SQL select statement selecting all schools. I want it in the field above. I have tried using json_encode but it doesn't quite seem to work as expecting. I don't know how it really works.

<?php
  require_once('config.php');

    try {

    $stmt = $db->query('SELECT * FROM school ORDER BY naam ASC');
    while($row = $stmt->fetch()){
                                    
    $school = ''.$row['naam'].'';
    $schools = array("$school");
    echo json_encode($schools);

  }
} catch(PDOException $e) {
 echo $e->getMessage();
}
?>

But, the output is this:

["!mpulse Kollum, school van OSG Piter Jelles"]["!mpulse Leeuwarden, school van OSG Piter Jelles"]["'s Gravendreef College Henri Faasdreef"]

...and so further.

And the output I actually want is this:

["!mpulse Kollum, school van OSG Piter Jelles","!mpulse Leeuwarden, school van OSG Piter Jelles's","Gravendreef College Henri Faasdreef"]

How can I fix this?

CodePudding user response:

Use it like

<?php
  require_once('config.php');
 try {
    $schools = array();
    $stmt = $db->query('SELECT * FROM school ORDER BY naam ASC');
    while($row = $stmt->fetch()){
                                    
      $schools[] = $row['naam'];

    }
    echo json_encode($schools);
} catch(PDOException $e) {
 echo $e->getMessage();
}
?>
  • Related