JSON encode with SQL and PHP query

2

Good morning, everyone. This question I have already seen in several issues but I do not understand very well what is the problem of why it does not enter the results in an array. I know that the query returns results.

I leave code:

function jsonEcho(){
include('conn.php');
$servername = "localhost";


$ttenQ="SELECT 'id', 'nombre_cock', 'categoria_fk', 'descripcion','Preparacion', 'img_path', 'puntuacion' FROM 'def_cockteles'  ORDER BY 'puntuacion' DESC LIMIT 10";
$resultado = mysqli_query($conexion,$ttenQ);

$topTen = array();

$rowcount=mysqli_num_rows($resultado);
printf("Result set has %d rows.\n",$rowcount);
while ($row=mysqli_fetch_array($resultado)) {

    $topTen[]=array('ruta'=> $row["img_path"],'descripcion'=>$row["descripcion"]);
}

 return json_encode($topTen);
}

print_r(jsonEcho());

?>

Thanks in advance

    
asked by RafaelM 11.10.2016 в 17:36
source

4 answers

1

Replace the return with echo and voila, that will show you the json.

echo json_encode($topTen);

Greetings

    
answered by 11.10.2016 в 21:31
0

If you are doing it with ajax you have to comment on this line printf("Result set has %d rows.\n",$rowcount); and if you want to see the result of that line of code it would be good if you also get the fix. When you make a ajax request, the correct thing is that only the json_encode is printed. Try this code:

$topTen = array();

$rowcount=mysqli_num_rows($resultado);
$topTen['rowcount'] = "Result set has $rowcount rows.\n";
while ($row=mysqli_fetch_array($resultado)) {    
    $topTen['data'][]=array('ruta'=> $row["img_path"],'descripcion'=>$row["descripcion"]);
}
return json_encode($topTen);
    
answered by 11.10.2016 в 17:45
0

Test by setting the Content-Type header:

<?php
$data = /** lo que sea que necesitas serializar **/;
header('Content-Type: application/json');
echo json_encode($data);
?>

Original answer: link

    
answered by 11.10.2016 в 21:15
0

Test:

$topTen = array();
while($row = mysqli_fetch_assoc($resultado)) {
  $topTen[] = $row;
}
print json_encode($topTen);

and remove the printf

    
answered by 14.11.2016 в 10:45