Array only prints last record

1

I have the following structure.

global.php

<?php 
define("DB_HOST","localhost");
define("DB_NAME", "prueba");
define("DB_USERNAME", "root");
define("DB_PASSWORD", "");
define("DB_ENCODE","utf8");
?>

conexion.php

<?php 
require_once "global.php";
$conexion = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
mysqli_query( $conexion, 'SET NAMES "'.DB_ENCODE.'"');
if (mysqli_connect_errno())
{
    printf("Falló conexión a la base de datos: %s\n",mysqli_connect_error());
    exit();
}
if (!function_exists('ejecutarConsulta'))
{
    function ejecutarConsulta($sql)
    {
        global $conexion;
        $query = $conexion->query($sql);
        return $query;
    }
}
?>

subcategory.php

<?php 
require "Conexion.php";
Class Subcategoria
{
    public function __construct()
    {
    }
    public function seleccionar($idcategoria)
    {
        $sql = "select s.nombre FROM subcategoria s INNER JOIN categoria c on s.idcategoria=c.id WHERE s.idcategoria='$idcategoria'";
    return ejecutarConsulta($sql);  
    }
}
?>

prueba.php

<?php 
header("Content-Type: application/json");
    require_once "Subcategoria.php";
    $subcategoria = new Subcategoria();
    $rspta = $subcategoria->seleccionar($_GET["id"]);
    while($reg = $rspta->fetch_object()){
    $datos = array(
        'Detalles' => array(
            array(
            'nombre'=>$reg->nombre,
        ),
    ),
    );
}
echo json_encode($datos);
?>

The problem that arises is that the array only prints the last record of the query:

{"Detalles":[{"nombre":"aceite"}]} // este el resultado
//lo he hecho con foreach, for y es el mismo resultado.

the result should be

{"Detalles":[{"nombre":"aceite"}],[{"nombre":"filtros"}],[{"nombre":"bujias"}]}
    
asked by JohnL 30.01.2018 в 14:32
source

1 answer

2

The error seems simple, you only make the assignment to your array = in the file prueba.php . you should add a new element for each iteration. In the while change the $datos = ... per $datos[] = ...

while($reg = $rspta->fetch_object()){
  //agrega elementos
  $datos[] = array(
      'Detalles' => array(
          array(
          'nombre'=>$reg->nombre,
      ),
  ),
);

If you want to have a single key and then add values to it, you could do so by declaring the array before and then adding it as the previous example.

//declarar el array fuera con la clave detalles
$array = array(['detalles'=>'']);

while($reg = $rspta->fetch_object()){
    $datos['detalles'][] = array(
      'nombre'=>$reg->nombre);
}
    
answered by 30.01.2018 / 14:37
source