json_encode does not return anything

2

What I'm doing

I'm pulling data through PHP with a list of cities to create a graph with Javascript, and I realized that it was not returning the data, so I accessed the file that takes the data from the database and does the conversion with the json_encode to see what happened.

What happened

The method to get the cities is working, and when I give print_r in the result it is shown correctly, but as soon as I give a echo json_encode($resultado) the page is empty.

My code

Calling Method and parsing

$result = $cidadeDAO->getCidades();
echo json_encode($result);

Method for obtaining cities

public function getCidades() {
        $stmt = self::$connection->prepare("SELECT cidade FROM cd_unidades order by cidade ASC");
        $stmt->execute();
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

Result print_r

Array
(
    [0] => Array
        (
            [cidade] => Araraquara
        )

    [1] => Array
        (
            [cidade] => Bauru
        )
)
    
asked by anonymous 15.06.2015 / 15:19

2 answers

1

Try transforming the output of it:

$cidades = array();
while($row = $result->fetch()) {
{
   $cidade = array(
       'cidade' => $row['cidade'],
   );
   array_push($cidades, $cidade);
}
$json = json_encode($cidades);
    
15.06.2015 / 15:31
2

Make sure the encodings are correct, use utf8_encode to do the conversion and test:

$cidades = array();
while($row = $result->fetch()) {
{
   $cidade = array(
       'cidade' => utf8_encode($row['cidade']),
   );
   array_push($cidades, $cidade);
}
$json = json_encode($cidades);
  

If it works, check the PDO for it to open the connection in UTF-8

$db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'')); 

Source: link

    
15.06.2015 / 15:43