Undefined index array Pdo

Asked

Viewed 133 times

-1

good people I’m trying to get the id of a user who logged in and saved in the session but , not working, I make a query in the bank when logging in and turn the result into an array to pick up the id and store in Session , but this giving Undefined index id , This is the code that logs in

     try{
 $select = ("SELECT * FROM usuario WHERE nome=:usuario AND senha=:senha AND status=1");
 $logarusuario = $pdo->prepare($select);
 $logarusuario->bindValue(":usuario", $usuario);
 $logarusuario->bindValue(":senha", $senha);
 $logarusuario->execute();
 $linhas = $logarusuario->rowCount();
 $result = $logarusuario->fetchAll(PDO::FETCH_OBJ);


 if($linhas > 0){
    $_SESSION['usuario'] = $usuario;
    $_SESSION['senha'] = $senha;
    $_SESSION['id'] = $result['id'];
    $_SESSION['logged_success'] = 'você foi logado com sucesso';
    header(5,"Location:../logado.php");
   }else{
    header("Location:../index.php");
    echo "Dados Digitados Incorretos";
   }
}catch(PDOException $e){
   echo $e;
}
?>
  • 1

    When using PDO::FETCH_OBJ you trade the [] for ->

  • 1

    Also, when using the fetchAll it will return a collection. Exchange the [] for -> would be the case to use within a loop, foreach for example.

1 answer

0

The fetchAll function returns a multidimensional array. You shouldn’t just do $result['id']. Example of what is returned:

Array
(
    [0] => Array
        (
            [id] => 1

        ),
    [1] => Array
        (
            [id] => 2

        )
)

So you could do $result[0]['id'], supposing that there will always be a user returned in that code snippet.

Browser other questions tagged

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