I errrely print the json in php

0

I am trying to bring the data of a bd in mysql, it brings me the last data that has been entered into the bd, but it does not bring all the data

<?php 
    include('conexion.php');
    $json = array();
    $link = conectarse();
    $select = "SELECT * FROM peliculas";
    $resultado = mysqli_query($link,$select);
    while ($registro = mysqli_fetch_array($resultado)) {
        $json['peliculas'] = $registro;
    }
    mysqli_close($link);
    echo json_encode($json, JSON_UNESCAPED_UNICODE);
?>
    
asked by Julian Felipe 11.06.2018 в 05:38
source

3 answers

2

I see two problems, the first that you are overwriting the results and in the variable $json you will always have the last record. try putting this:

  $json['peliculas'][] = $registro;

Another problem is that you are using mysqli_fetch_array to recover the result without indicating the way you want the result, so for each record you return an associative and numeric array at the same time duplicating the records. This can cause problems when converting it to json .

Try changing the line like this:

while ($registro = mysqli_fetch_assoc($resultado))

Here I leave your modified code:

 <?php 
    include('conexion.php');
    $json = array();
    $link = conectarse();
    $select = "SELECT * FROM peliculas";
    $resultado = mysqli_query($link,$select);
    while ($registro = mysqli_fetch_assoc($resultado)) {
        $json['peliculas'][] = $registro;
    }
    mysqli_close($link);
    echo json_encode($json, JSON_UNESCAPED_UNICODE);
    ?>

Here more information on mysqli_fetch_assoc and mysqli_fetch_array

EDITED BY COMMENT

To debug possible errors in the formation of json the function json_last_error_msg is very useful () using it in the following way:

echo json_last_error_msg();

For example, it is common to get the following error:

  

Badly formed UTF-8 characters, possibly coded in a way   incorrect

This would be solvable by defining the charset of the database in your code as follows:

mysqli_set_charset($link, 'utf8');

    
answered by 11.06.2018 в 09:25
0

You are overwriting the data in each loop path:

while ($registro = mysqli_fetch_array($resultado)) {
    $json['peliculas'] = $registro;
}

try to give different indexes:

$i=0;
while ($registro = mysqli_fetch_array($resultado)) {
    $json[$i] = $registro;
    $i++;
}
    
answered by 11.06.2018 в 09:02
0

I already solved it, I made a change in the code, it was this:

while ($registro = mysqli_fetch_assoc($resultado)) {
    $json['idPeliculas'][] = $registro['idPeliculas'];
    $json['Nombre'][] = $registro['Nombre'];
    $json['Sipnosis'][] = $registro['Sipnosis'];
    $json['Calificacion'][] = $registro['Calificacion'];
    $json['Duracion'][] = $registro['Duracion'];
}
    
answered by 11.06.2018 в 18:31