为什么我打印会话时会出现这种情况: 数组([name] => [pass] =>)?
以下是我的代码
用户输入的主页面,login.php:
<form action="" method="post">
<div class="imgcontainer">
<img src="KBR2xN6.jpg" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" required>
<br />
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required>
<button type="submit">Login</button>
<button type="reset" class="cancelbtn">Reset</button>
</div>
</form>
连接到本地服务器connections.php:
$host = "localhost";
$username = "root";
$password = "";
$database = "netbook 1 malaysia";
try {
$connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo 'Connection Failed : '.$ex->getMessage();
}
我的会话页面,session.php:
session_start();
include('connections.php');
$username = $_POST['name'];
$password = $_POST['pass'];
$sql = "SELECT * FROM pengguna WHERE username = '$username' AND password = '$password'";
$result = $connect->query($sql);
if($result->rowcount()>0){
foreach($result AS $data){
$_SESSION['name'] = $data['name'];
$_SESSION['pass'] = $data['pass'];
echo "<script>alert('Login Success');
window.location.href='view.php';
</script>";
}
}
else {
echo "<script>alert('Login Failed');
window.location.href='login.php';
</script>";
}
也许我的数据库失败了?
答案 0 :(得分:0)
$result
包含资源,而不是直接包含数据库数据。
当我们只期望一行表格数据库时,不需要循环。使用一个循环,您只需要在名称/传递会话中,它将在您的代码中被覆盖以用于最后一个。
$data = $result->fetch_assoc();
$_SESSION['name'] = $data['name'];
$_SESSION['pass'] = $data['pass'];
print_r($_SESSION);
请注意,没有理由在会话中存储密码,与数据库中的商店密码一样作为明文。
答案 1 :(得分:-1)
您打印会话数组的位置?如果在view.php文件上打印会话,请确保在view.php文件上启动会话。