Database data comes incomplete

Asked

Viewed 26 times

1

Good afternoon, everyone,

I have two data in the database, but doing select only 1 appears, pq?

<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

include_once("con.php");

$pdo = conectar();

$opcao = $_GET['opcao'];

switch ($opcao) {
    case 'pegaCategoria':

    $pegaCategoria=$pdo->prepare("SELECT * FROM categoriaComum");
    $pegaCategoria->execute();

    $return = array();

    while ($linhaCateAdmin=$pegaCategoria->fetch(PDO::FETCH_ASSOC)) {

        $idcategoriaComum = $linhaCateAdmin['idcategoriaComum'];
        $categoriaComum = $linhaCateAdmin['categoriaComum'];

        $return = [
            "idcategoriaComum" => $idcategoriaComum,
            "categoriaComum" => $categoriaComum
        ];

    }

    echo json_encode($return);

    break;
?>

And from the image below, you can see that I have two data in the table.

inserir a descrição da imagem aqui

And on the console, it displays 1 only.

inserir a descrição da imagem aqui

  • 1

    $return is being reallocated all the time, you need to add a new item in the array. $return[] = ['chave' => valor]

1 answer

4


So you’re rewriting the value and you end up with only the last returns in the last loop, do this:

...
$return = array();
while ($linhaCateAdmin=$pegaCategoria->fetch(PDO::FETCH_ASSOC)) {

        $return[] = [
            "idcategoriaComum" => $linhaCateAdmin['idcategoriaComum'],
            "categoriaComum" => $linhaCateAdmin['categoriaComum']
        ];

}
echo json_encode($return);
break;
...
  • Valeu Miguel...

  • You’re welcome @Gustavosevero

Browser other questions tagged

You are not signed in. Login or sign up in order to post.