将user_id添加到Session mysql中

时间:2017-01-26 17:34:59

标签: php mysql database session

我试图弄清楚如何将我的user_id从我的数据库添加到像我的用户名这样的会话。我想这样,当我登录时,我可以调用会话来根据用于登录的用户名调用用户ID帖子。

我该怎么做?

我的登录php:

<?php

session_start();

$connect = mysql_connect( "localhost", "user", "pass") or die('Database could not connect');
$select = mysql_select_db( "database", $connect) or die('Database could not select');

if (isset($_POST['submit'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    chckusername($username, $password);
}

function chckusername($username, $password){

    $check = "SELECT * FROM users WHERE username='$username'";
    $check_q = mysql_query($check) or die("<div class='loginmsg'>Error on checking Username<div>");

    if (mysql_num_rows($check_q) == 1) {
        chcklogin($username, $password);
    }
    else{
        echo "<div id='loginmsg'>Wrong Username</div>";
    }
}

function chcklogin($username, $password){

    $login = "SELECT * FROM users WHERE username='$username'  and password='$password' ";
    $login_q = mysql_query($login) or die('Error on checking Username and Password');



print_r($lohin_q);

    if (mysql_num_rows($login_q) == 1){



        header('Location: http://ct6014-williams.studentsites.glos.ac.uk/pages-multi-page/home.php');        
        $_SESSION['username'] = $username;
        $_SESSION['user_id'] = $userid; //this is where I want to store the user id

    }
    else {
        echo "<div id='loginmsg'>Wrong Password </div>"; 

    }
}
?>

on home.php:

<?php echo "Your username is " . $_SESSION["username"] . "."; ?>    
     <?php echo "Your id is " . $_SESSION["user_id"] . "."; ?>

数据库名称:

user_idusernameuser_first_nameuser_last_nameuser_emailpassworduser_reg_date

修改

啊,我忘了说,我用过include('login.php');我以用户身份登录时创建了会话。第一个用户名会话回声,但我似乎无法弄清楚如何设置user_id会话

1 个答案:

答案 0 :(得分:1)

Body函数中,使用mysql_fetch_array()函数从结果集中获取行,并将所需的用户数据分配给chcklogin()。因此,请按以下方式更改$_SESSION块,

if (mysql_num_rows($login_q) == 1){ ...

旁注:不要使用if (mysql_num_rows($login_q) == 1){ $row = mysql_fetch_array($login_q); $_SESSION['username'] = $row['username']; $_SESSION['user_id'] = $row['user_id']; header('Location: http://ct6014-williams.studentsites.glos.ac.uk/pages-multi-page/home.php'); exit(); } else { echo "<div id='loginmsg'>Wrong Password </div>"; } 函数,从PHP 5.5开始不推荐使用它们,并且在PHP 7.0中完全删除它们。请改用mysqlipdoAnd this is why you shouldn't use mysql_* functions