所以我有一个使用php mysqli工作得很好的登录页面,但是没有准备好所以我通常使用mysqli_real_escape来保护数据。
但是我现在正在迁移到使用预处理语句,用我的注册页面管理这个,这很好。
这是我未准备好的登录代码:
$loginQuery = "select * from user where user_name = '$user_name' AND password = '$password'";
$result = mysqli_query($con,$loginQuery);
if(mysqli_num_rows($result)){
$row = mysqli_fetch_array($result);
// password verify
if (password_verify($password, $row['password'])) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = strtoupper($row['user_name']);
$user_type = strtolower($row['user_type']);
if(strtolower($user_type) == 'member'){
$_SESSION['user_type'] = 'member';
//header('Location: member-dashboard-home.php');
header('Location: profile.php');
}elseif(strtolower($user_type) == 'admin' || strtolower($user_type) == 'leader'){
$_SESSION['user_type'] = strtolower($user_type);
//header('Location: admin-dashboard-home.php');
header('Location: profile.php');
}
}else{
$_SESSION['main_notice'] = "Invalid login details!";
header('Location: '.$_SERVER['PHP_SELF']);exit();
}
以下是我使用预备声明的努力。
$stmt = $mysqli->prepare("SELECT user_name FROM user WHERE user_name = ? ");
$stmt->bind_param('s', $user_name);
$stmt->execute();
$stmt->bind_result($user_name);
if($res = $stmt->num_rows()){
$row = $stmt->fetch_array($res);
// password verify
if (password_verify($password, $row['password'])) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = strtoupper($row['user_name']);
$user_type = strtolower($row['user_type']);
if(strtolower($user_type) == 'member'){
$_SESSION['user_type'] = 'member';
//header('Location: member-dashboard-home.php');
header('Location: profile.php');
// exit;
}elseif(strtolower($user_type) == 'admin' || strtolower($user_type) == 'leader'){
$_SESSION['user_type'] = strtolower($user_type);
//header('Location: admin-dashboard-home.php');
header('Location: profile.php');
//exit;
}
}else{
$_SESSION['main_notice'] = "Invalid username OR password details, please try again!";
header('Location: '.$_SERVER['PHP_SELF']);exit();
}
}
当我尝试登录时,我没有收到任何错误代码,但表单只是返回空白而没有重定向到用户个人资料。
我不认为这是重定向问题或是吗?
我没有正确安排$stmt
,希望你的家伙能看到我能做的事。
提前致谢
答案 0 :(得分:1)
根据您的评论,
我确实包含在顶部,我收到此错误提示:未定义的变量:/home/connection.php中的mysqli ... ...
在这里查看你的代码,
$con
您的连接处理程序是$mysqli
,而不是$con = new mysqli("localhost", "***", "***", "***");
if ($con->connect_errno) {
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
,它应该是这样的:
$stmt = $con->prepare("SELECT * FROM user WHERE user_name = ? ");
$stmt->bind_param('s', $user_name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
// username exists
$row = $result->fetch_array();
// your code
}else{
// username doesn't exist
// your code
}
更新(1):按以下方式更改您的代码,
{{1}}