someone knows why the json does not print

1
$from 
$to = 20;
$query = "SELECT idempleados,nombre,apellidos FROM empleados LIMIT ?,?";
$result = $mysqli->prepare($query);
$result->bind_
param('ii', $from, $to);
$result->execute();
/* bind result variables */
$result->bind_result($idempleados,$nombre,$apellidos);
/* fetch values */
while ($result->fetch()){
    $empleados[] = array(
        'idempleados' => $idempleados,
        'nombre' => $nombre,
        'apellidos' => $apellidos
    );
}
echo json_encode($empleados);
/* close statement */
$result->close();
/* close connection */
$mysqli->close();
?>

This code does not print the json.

But when I give an index to the arrangement $ employees if I print the index I give it. for example I give the index 0 and if you print it.

...

echo json_encode($empleados[0]);

/* close statement */
   ...

EDIT

If I do print_r ($ employees) I receive

I am already solved thanks to all who responded, I help the answer of @sioesi

so I leave the code

while ($result->fetch())
    {
    $empleados[] = array(
    'idempleados' => $idempleados,
        'nombre' => utf8_encode($nombre),
        'apellidos' => utf8_encode($apellidos)
    );
    }
  echo json_encode($empleados,JSON_UNESCAPED_UNICODE);

    
asked by daniel del rio cruz 28.10.2016 в 15:28
source

2 answers

3

Your problem is the characters ... if you look at the element of your arreglo[7] and arreglo[11] the last names have a Ñ. That's why it does not work, you must make sure that they have UTF-8 in the database. In the database it must be poorly saved.

while ($result->fetch()){
    $empleados[] = array(
        'idempleados' => $idempleados,
        'nombre' => utf8_encode($nombre),
        'apellidos' => utf8_encode($apellidos)
    );
}
echo json_encode($empleados, JSON_UNESCAPED_UNICODE);

EDIT

In the PHP documentation there is an example and you can read more about it

PHP JSON_ENCODE

As you comment your database is configured with InnoDB and utf8_general_ci , therefore the error is from the file in which you save the values ... You must also configure it with UTF-8

    
answered by 28.10.2016 / 15:42
source
0

It is because your resulting arrangement is entered into an object, so at the time of iterating it would be $ employees [0] ... $ employees [1] ... etc. If it's just going to be a record that you're going to enter instead of putting it in as an arrangement, enter it directly.

    $empleados = [
        'idempleados' => $idempleados,
        'nombre' => $nombre,
        'apellidos' => $apellido
        ];

If you want to print with echo all your object you can go through it in a bucket or enter it directly.

while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}

edit : I saw that you use mysqli and my solution was oriented to PDO.

    
answered by 28.10.2016 в 15:41