Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use json_encode?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["!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?

>Solution :

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();
}
?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading