Json PHP and Mysql

2

I'm working on a personal project with an open database, and I need a JSON file from a MYSQL query, I've been trying to solve this problem for a few days now and I'm having a hard time getting the name of the My data. Example: I make a query to list all states, I can get the json with the ID, UF, Region, when I put the field name, it returns nothing to me and gives the error Resource interpreted as Document but transferred with MIME type application / json: " link ". My goal is to get all the data from the query and return a JSON to deal with GeoCharts.

<?php

$con = mysqli_connect("localhost","root","3919223","DatasusNew") or die("Error " . mysqli_error($con));
mysqli_query('SET NAMES utf8;');
$var = array();
$sql = "SELECT * FROM estados";
$result = mysqli_query($con, $sql);

foreach ($result as $row) {
    $return[] = [ 
        'nome' => $row['nome'],
        'idEstado' => $row['idEstado'],
        'uf' => $row['uf'],
        'regiao' => $row['regiao']

    ];
}
$dbh = null;

header('Content-type: application/json');
echo json_encode($return);

?>

Has anyone ever had this problem? Or any tips?

    
asked by anonymous 29.09.2016 / 01:45

3 answers

2

My friend, I got it !! The final code is ... Thank you

   if ($result = mysqli_query($con, $sql))
   {

    while($row = $result->fetch_object())
    {
        foreach($row as $key => $col){
           $col_array[$key] = utf8_encode($col);
        }
        $row_array[] =  $col_array;

    }

    echo json_encode($row_array, SON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
mysqli_close($con);
?> '

It's coming back like this: [

29.09.2016 / 02:33
1

It does the following: use mysqli_fetch_assoc() , it returns the results associated with the table name, I think it looks something like this:

    <?php

        $con = mysqli_connect("localhost","root","3919223","DatasusNew") or die("Error " . mysqli_error($con));
    mysqli_query('SET NAMES utf8;');
        $var = array();
        $sql = "SELECT * FROM estados";
        $result = mysqli_query($con, $sql);
        $rows = array();
        while($each = mysqli_fetch_assoc($result)){
            $rows[] = $each;
        }
        header('Content-type: application/json');
        echo json_encode($rows);
     ?>
    
29.09.2016 / 02:31
0

Answer:

$lista_json = array("objects_array" => array());
foreach($result as $row){
     $obj = array (
         "nome" => utf8_encode($row['nome']),
         "idEstado" => $row['idEstado'],
         "uf" => utf8_encode($row['uf']),
         "regiao" => utf8_encode($row['regiao'])
     );

     array_push($lista_json["objects_array"], $obj);
}

header('Content-type: application/json');
echo json_encode($lista_json);

Did it work?

References:

Convert object to json in PHP

PHP: utf8_encode

    
29.09.2016 / 02:14