Problems with php PDO

Asked

Viewed 37 times

2

Good Afternoon, I am trying to access my database to take the 12 countries present in the table and return an array with the id and name of the 12 countries but my code is only returning 1 position in the array that is the first country only, someone could help me please. Ever since I thank

function recuperaPaises(){
    //Função que pega os países do banco e jogam no array de países da classe
    $conexao = new DB;
    $conexao=$conexao->getConnection();
    $rs = $conexao->prepare("SELECT * FROM paises");
    if ($rs->execute()){

  $row = $rs->fetch(PDO::FETCH_OBJ);
  return $row;

}
else{

  $flash="OPS!... ouve algum erro em nosso Sistema. Por Favor contate administrador!";
  echo $flash;
}

}

1 answer

3


To return all items of a query use the method fetchAll(), because only put fetch() is to return only one item of the result, usually in the search of data of 1 customer, data of a purchase, etc., ie to bring a collection of data use fetchAll(), example:

Modified code:

function recuperaPaises()
{
    //Função que pega os países do banco e jogam no array de países da classe
    $conexao = new DB;
    $conexao=$conexao->getConnection();
    $rs = $conexao->prepare("SELECT * FROM paises");
    if ($rs->execute()){

      $row = $rs->fetchAll(PDO::FETCH_OBJ);
      return $row;

    }
    return null;
}

I made a modification if you do not bring result return null out of this method call one can work better the feedback information.

References

Browser other questions tagged

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