I will show how to do it in both PDO and MySQLi.
1. Using PDO
If you use the fetchAll
method in PDO. You no longer need to read the data within a loop, since this method:
Returns an array that contains all the rows in the set of
results
Source: fetchAll
in the PHP Manual
Therefore, the code could look like this:
$pdo=new PDO("mysql:dbname=usuario;host=localhost","root","root");
$statement=$pdo->prepare("SELECT * FROM usuario WHERE estado = 1 ORDER BY idusuario desc;");
$statement->execute();
if (!$statement){
echo 'Error al ejecutar la consulta';
}else{
echo 'intentando obtener registros <br>';
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
As the Manual says, the code will store in the variable $results
all the results when using fetchAll
. In addition, it will store them in an associative array that, in the json, will correspond to a set of key / value data.
2. Using MySQLi
MySQLi has a fetch_all
method, but this is only available if you have installed the mysqlnd
driver. As we are not sure of that, and since we do not know if your code in the future could be executed on a computer that does not have that driver, we'd better use a code that is valid for any system.
We will recover the data with the method fetch_assoc
, then we will read them inside a loop to create the array with all the rows.
$mysqli = new mysqli($host_name, $user_name, $pass_word, $database_name, $port); //tu conexion
//Consulta
$sql = "SELECT * FROM usuario WHERE estado = 1 ORDER BY idusuario desc";
//Se envía la consulta y se almacena en la variable $resultado
$resultado = $mysqli->query($sql);
//Se verifica si hay resultados y se crea un array asociativo usando ->fetch_assoc()
if ($resultado)
{
for ($arrDatos = array (); $row = $resultado->fetch_assoc(); $arrDatos[] = $row);
echo json_encode($arrDatos);
/* liberar el conjunto de resultados */
$resultado->free();
}else{
print_r("No se encontraron datos, verifique su consulta SQL o la conexión a la BD");
}
/* cerrar la conexión si es preciso */
$mysqli->close();
3. About the character set
Sometimes working with JSON gives errors because the data is coming badly encoded because at the time of creating the connection, an appropriate character set was not established.
To set the character set in PDO
If you want to do it after creating the connection object, you can do this:
$pdo->exec("set names utf8");
If you want to do it in the constructor, you pass it in an array, at the end of the constructor (see link at the end of this section).
To set the character set in MySQLi
You can also do it once the object is created:
$mysqli->set_charset("utf8")
Or indicate it in the constructor.
For more details about the coding problem, you can consult the answer to this question: Why the Inspector Character ( ) appears in some data obtained from the Database?