public function getLoginInfo($username,$password){
$conn=DB::connect();
session_start();
$sql="select * from owner where o_email='".mysql_real_escape_string($username)."' and o_password='".mysql_real_escape_string($password)."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION['email']=$username;
$_SESSION['password']=$password;
}
header("location:../owner/owner_dashboard.php");
} else {
header("location:../owner/owner_login.php");
}
$conn->close();
}
我已经在会话数组中添加了用户名和密码,但我也希望将id保存到会话数组中,该数据存储在数据库中作为“o_id”
答案 0 :(得分:0)
你过程比过程复杂。 mysql_ extensions也被弃用了。因此,你不应该使用它们。使用防止sql注入的prepare语句。此外,您无需在会话中存储密码。您的密码应作为哈希值存储在数据库中,因此将其存储在会话中对您来说不可靠。找到与您搜索的用户名和密码匹配后,只需将用户名存储在会话中即可。在您的应用程序中,您可以与登录区域的用户名进行比较。我将您的代码修改为更清晰的解决方案。我不得不做一些假设,例如你的conn是一个PDO。
public function getLoginInfo($username,$password)
{
//start the session only if it has not started somewhere else
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
//try to query the database
try {
$conn = DB::connect();
$sql = 'Select * from owner where o_email= :email and o_password = :password';
$conn->prepare($sql);
$res = $conn->execute(array(':email' => $username, ':password' => $password));
//check if the data exist. only true if result set is greater than 0
if ($res->rowCount() > 0)
{
$_SESSION['email']=$username;
header("location:../owner/owner_dashboard.php");
exit("login success, redirecting to dashboard...");
}
//doesnt exit so go back to login
header("location:../owner/owner_login.php");
exit('Invalid username or password. Redirecting back to lgoin...');
}
//Error is only output for debugging purpose. I would encourage turn this off in production
catch(Exception $e)
{
print_r($e->getMessage());
}
}
答案 1 :(得分:0)
首先,必须清楚的是,如果您要查询日志记录 在,然后查询将只返回一行,所以使用while是 无意义的。
public function getLoginInfo($username,$password){
$conn=DB::connect();
session_start();
$sql="select * from owner where o_email='".mysql_real_escape_string($username)."' and o_password='".mysql_real_escape_string($password)."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Edited from here
// output data of each row
$row = $result->fetch_assoc();
$arraydata[$row['id']] = $row;
$_SESSION['user_info']=$arraydata;
$_SESSION['current_loggedin_id']=$row['id'];
header("location:../owner/owner_dashboard.php");
} else {
header("location:../owner/owner_login.php");
}
$conn->close();
}