Pick up specific fetchAll item in PHP

Asked

Viewed 545 times

-1

I’m using the code:

$lista = $db->query('select * from tabela') or trigger_error($db->error);
$lista->execute();
$item = $lista->fetchAll(PDO::FETCH_ASSOC);
$mes = 1;
    while ($mes < 13){
    echo $obito[$mes]['total']; //quero listar o total aqui
    $mes++;
}
  • 3

    Hi Italo this $db is a PDO instance??

  • 2

    what is $db? what is queryMes? code missing before those lines.

  • is a yes instance

  • 1

    May echo $item[3]['nome'];

  • @Virgilionovic query works well, is that I simplified the code above. the variable $item should list all my items

  • 2

    @Italorodrigo do not simplify, put, really what you are doing, everything relevant and in the details.

  • 1

    I will edit the question

  • 1

    use the print_r or var_dump to know if it comes as array or object. If it is a PDO instance, it must come as object.

  • edited and posted the code I’m using now

  • 1

    That $lista->execute() doesn’t make any sense. Gives a print_r($obito) and ask the question, so everyone knows the structure of it.

  • thanks to all, I managed to solve

Show 6 more comments

1 answer

3


You can try the code below;

$host = 'localhost'; // endereço do servidor de banco de dados.
$dbname = 'seu_banco_de_dados'; //nome de sua base de dados
$user   = 'root'; // seu usuário do banco
$pass   = ''; // sua senha do banco

$db = new PDO('mysql:host='.$host.';dbname='.$dbname,$user,$pass);
$lista = $db->prepare(queryMes($ano,$ibge));
$lista->execute();
$item = $lista->fetchAll(PDO::FETCH_ASSOC);

echo $item[3]['nome'];

Or you can use the for to list...

$host = 'localhost'; // endereço do servidor de banco de dados.
$dbname = 'seu_banco_de_dados'; //nome de sua base de dados
$user   = 'root'; // seu usuário do banco
$pass   = ''; // sua senha do banco
$lista = $db->prepare(queryMes($ano,$ibge));
$lista->execute();
$item = $lista->fetchAll(PDO::FETCH_ASSOC);

foreach($item as $info) {
    echo $info['nome']."<br/>";
}
  • in the line $obitos->execute(); gives Fatal error: Call to Undefined method mysqli_result:execute()

  • 2

    Ah ítalo you are not using the PDO?

  • I edited and put the code I’m using now, please take a look

  • 1

    Correct the response, change the values for your database data.

  • worked yes, thanks. Voce can explain the difference between: $db = new mysqli(); and $db = new PDO();

  • 1

    are different objects. just check in the manual. PDO Manual and Mysqli Manual

  • without wanting to abuse your good will, just one more detail to complete the work. how to know if $item[$i] exists?

  • 2

    yes put if(isset($item[$i]) { echo 'Exists'; }

Show 3 more comments

Browser other questions tagged

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