Bring everything from MySql with PHP and show in JSON

1

I have a problem with PHP and JSON. What I do is try to bring all the data from the database, but it only shows me the first one. If I put a WHERE it brings me the right one but I want everyone and it only brings me the first one. I do not understand what the error may be, I appreciate your help.

$hostname_localhost="localhost";
$database_localhost="drive";
$username_localhost="root";
$password_localhost="";

$json=array();

 $conexion = new mysqli($hostname_localhost, $username_localhost,   $password_localhost, $database_localhost);    

 $consulta="SELECT * FROM comercio";

 $resultado = mysqli_query($conexion, $consulta);

 if($registro=mysqli_fetch_array($resultado)){
     $json['comercios'][]=$registro;  

 }else{
     $resultar["comercios"]=0; 
 }

mysqli_close($conexion);
echo json_encode($json);
    
asked by Juampi 22.11.2018 в 16:43
source

2 answers

1

The solution is to go through the array of the db and pass it to the JSON. But it will only grasp the first data.

$hostname_localhost="localhost";
$database_localhost="drive";
$username_localhost="root";
$password_localhost="";

$json=array();

  $conexion = new mysqli($hostname_localhost, $username_localhost, $password_localhost, $database_localhost);    

  $consulta="SELECT * FROM comercio";

    $resultado = mysqli_query($conexion, $consulta);

     while($registro=mysqli_fetch_assoc($resultado)){
         $json['comercios'][]=$registro;  

     }

    mysqli_close($conexion);
    echo json_encode($json);
    
answered by 22.11.2018 в 18:34
0

$ hostname_localhost="localhost"; $ database_localhost="drive"; $ username_localhost="root"; $ password_localhost="";

$ json = array ();

$ connection = new mysqli ($ hostname_localhost, $ username_localhost, $ password_localhost, $ database_localhost);

$ query="SELECT * FROM trade";

$resultado = mysqli_query($conexion, $consulta);

 while($registro=mysqli_fetch_assoc($resultado)){
     $json['comercios'][]=$registro;  

 }

mysqli_close($conexion);
echo json_encode($json);
    
answered by 23.11.2018 в 14:43