darkman
darkman

Reputation: 1003

PHP Json no consistent

I'm using a PHP page to get some data in my MySQL Database, I was using an xml structure to do that, but since I found JSON a little faster I decided to migrate all my webserver to that.

I use exactly the same code to retrieve data from the database, but the generated JSON can't get all the data; some fields like Description, and others like Nome, sometimes come as a null object. In the database everything is okay, and the XML script is also still running okay.

Here's the PHP script I'm using:

 <?php
    header('Content-type: application/json');

    $banco = "*******";
    $usuario = "*******";
    $senha = "*******";
    $hostname = "localhost";

    $conn = mysql_connect($hostname,$usuario,$senha); mysql_select_db($banco) or die( "Cant Connect MySQL");

    $result = mysql_query("SELECT * FROM users");
    $arrayOfChildren = Array(); 
    $i = 0;
    while($row = mysql_fetch_array($result))
    {
        $Balada = array(
             'Id'=>($row['Id']),
             'Nome'=>($row['Nome']),
             'Endereco'=> ($row['Endereco']),
             'Telefone'=>($row['Telefone']),
             'Description'=>($row['Descricao']),
             'Genero' => ($row['Genero']),
             'Pagamento' => ($row['FormasPagamento']),
             'NomeLista' => ($row['NomeLista'])
        );      
        $arrayOfChildren[] = $Balada;     
        $i++;
    }
    $myJSON = json_encode($arrayOfChildren);
    echo($myJSON);
    ?>

The generated JSON: Link

The XML for comparsion: Link

Upvotes: 1

Views: 147

Answers (2)

VDP
VDP

Reputation: 6420

Translation in the while loop is unnecessary, you can only make mistakes here. Just use mysql_fetch_object($result) in staid of mysql_fetch_array($result) and put the $row in the array.

$arrayOfChildren = Array(); 
while($row = mysql_fetch_object($result)) $arrayOfChildren[] = $row ;
echo json_encode($arrayOfChildren);

Or even better you could use PDO or MSQLi. Here is a MSQLi example:

$mysqli = new mysqli($hostname,$usuario,$senha, $banco);
$result = $mysqli->query("SELECT * FROM users");
$rows = Array(); 
while ($row = $result->fetch_object()) $rows[] = $row;
echo json_encode($rows);

Special chars can be a hassle too.. I think this question can be useful

Upvotes: 1

Elzo Valugi
Elzo Valugi

Reputation: 27856

If you using the portuguese "descrição" con tilde and cedille, probably you need to UTF8 encode the name of the key or the results, and probably have a mismatch key error between the column name and the key name. Check the results before exporting them to JSON to see if they include the description or not.

Upvotes: 1

Related Questions