Browse array and generate json with PHP

1

I have the following PHP code:

<?php
require_once('../conexion.php');
$con = mysqli_connect($host,$user,$pass,$db);
mysqli_set_charset($con, "utf8");
if ($stmt = mysqli_prepare($con, "select idusuario, cuenta from usuarios")) {
    //mysqli_stmt_bind_param($stmt, "ii", $start, $end);
    mysqli_stmt_execute($stmt)
    mysqli_stmt_bind_result($stmt, $idusuario, $cuenta);
    $result = array();
    while($row = mysqli_stmt_fetch($stmt)){
        $result["success"] = "true";
        $result["data"]["usuarios"] = array('iduser'=>$idusuario,'cuenta'=>$cuenta);
    }
    mysqli_stmt_close($stmt);
    header('Content-type: application/json; charset=utf-8');
    echo json_encode($result, JSON_FORCE_OBJECT);
 }
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
?>

The problem is that it only generates the JSON with a single value

    
asked by arglez35 01.08.2018 в 21:03
source

1 answer

3

The problem is that you are rewriting the value of users for each iteration. The solution is to return said value to an array. Something like this:

<?php
require_once('../conexion.php');
$con = mysqli_connect($host,$user,$pass,$db);
mysqli_set_charset($con, "utf8");
if ($stmt = mysqli_prepare($con, "select idusuario, cuenta from usuarios")) {
    //mysqli_stmt_bind_param($stmt, "ii", $start, $end);
    mysqli_stmt_execute($stmt)
    mysqli_stmt_bind_result($stmt, $idusuario, $cuenta);
    $result = array();
    $result["success"] = "true";
    while($row = mysqli_stmt_fetch($stmt)){            
        $result["data"]["usuarios"][] = array('iduser'=>$idusuario,'cuenta'=>$cuenta);
    }
    mysqli_stmt_close($stmt);
    header('Content-type: application/json; charset=utf-8');
    echo json_encode($result, JSON_FORCE_OBJECT);
 }
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
?>
    
answered by 01.08.2018 / 21:07
source