dsvtnz6350 2016-07-04 14:34
浏览 45
已采纳

PHP没有从MYSQL值设置会话变量

I am trying to set the session information if the user logs in successfully, but the values are not setting or are setting blank. I have session_start(); at the top of every page, including the login handler and all protected pages. Am I missing something?

$qry= "SELECT * FROM members WHERE username='$username';";
$result=mysql_query($qry);
$rows=mysql_fetch_object($result);

 //Check whether the query was successful or not
if($result) {
    if(mysql_num_rows($result) == 1) {
        if($rows->authlevel == "admin") {  //if it's not an admin no need to check password
            if($password = $rows->password) {
                session_regenerate_id();
                $member = mysql_fetch_assoc($result);
                $_SESSION['SESS_MEMBER_ID'] = $member['username'];
                $_SESSION['SESS_FIRST_NAME'] = $member['username'];
                $_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
                $_SESSION['SESS_LAST_NAME'] = $member['username'];
                session_write_close();
                header("location: admin_index.php");
                exit();
            } else {
                header("location: login-failed.php"); //change for bad password etc.
            }
        } else {
            header("location: login-failed.php");  //change for invalid user level ( you do not
        }
  } else {
        header("location: login-failed.php");
  }
} else {
    die("Query failed"); //change for username not found, or unknown username
}
?>

Note: Yes, I know, I should use MYSQLi or PDO, but I will implement that later. This is mostly for learning purposes so I'll get there eventually.

展开全部

  • 写回答

1条回答 默认 最新

  • dongsigan2044 2016-07-04 14:36
    关注
    if($password = $rows->password) {
    

    is true if there is a true-ish value to assign. You need to compare "==" not assign "=".

     if($password == $rows->password) {
    

    Edit: The next problem is that you are fetching an object at the top

    $rows=mysql_fetch_object($result);
    

    and then later fetch the next row as a associative array from the same $result - and the next row is empty (there is only 1 row in your result).

    $member = mysql_fetch_assoc($result);
    

    Instead you should be setting your session variables from the $row object you already have.

    $_SESSION['SESS_MEMBER_ID'] = $row->username;
    $_SESSION['SESS_FIRST_NAME'] = $row->username;
    $_SESSION['SESS_FIRST_NAME'] = $row->firstname;
    $_SESSION['SESS_LAST_NAME'] = $row->username;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部