-3
Hello, I’m studying PHP and I ended up getting stuck in a php system with login using sessions, I wanted the login page I created to take me to a user-only page, so I did it in an if that doesn’t allow people without login to enter it, but after creating it and testing I realized that even people who are logged in can not enter the users page, I imagine it is some kind of error with the sessions since the if includes a isset($_SESSION['id'])
as a requirement to be able to see the page. Codes of the pages below:
Login validation:
include("../conexao.php");
$usuario = $_POST["usuario"];
$senha = md5($_POST["senha"]);
$busca = "SELECT * FROM usuario WHERE usuario = :usuario and senha = :senha";
$stmt = $conn->prepare($busca);
$stmt->bindParam(":usuario", $usuario);
$stmt->bindParam(":senha", $senha);
$stmt->execute();
$linha = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$linha) {
echo "esse usuario não existe";
}else{
session_start();
$_SESSION['id'] = $linha->id;
$_SESSION['usuario'] = $linha->usuario;
header("location:menu.php");
}
?>
User page:
session_start();
if (isset($_SESSION['id'])) {
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>Pagina Usuario</h2>
<br><br>
<p> </p>
<a href="desconecta.php">desconectar</a>
<?php
}else{
header("location:desconecta.php");
} ?>
</body>
</html>
After stirring a little I got an error message, all I did was take the header(location:menu.php)
from the validation page, and now I get 2 errors when trying to log in:
These errors refer to the last two lines of the validation page, the line $_SESSION['id'] = $linha->id;
and the line $_SESSION['usuario'] = $linha->usuario;
$line is not an object, it is an array (because you used fetchAll)
– bfavaretto
Marcos, do as the bfavaretto said. Try trading for $stmt->fetch(PDO::FETCH_ASSOC) to see if it works.
– Gato de Schrödinger
I’m sorry but I’m still learning, would you be able to explain to me how this line of code would look so I can test? Would it just change $stmt->fetchAll(PDO::FETCH_ASSOC) to just fetch? Why if it was not working
– Marcus Lopes