使用电子邮件从DB中提取userId并在会话中存储用户ID

时间:2014-07-21 11:09:08

标签: php mysql

所以这是我的站点登录页面的代码,我希望它在用户登录时从数据库中提取用户ID并将其存储在会话数据中。我将在另一个页面中使用哪个从另一个表中提取值。

<?php
session_start();
//Connect to DB
include_once 'db_connect.php';

// escape variables for security
$Email = mysqli_real_escape_string($mysqli, $_POST['email']);
$Password = mysqli_real_escape_string($mysqli, $_POST['password']);
//password hashing
$Password = hash("sha256", $Password);

$sqli="SELECT * FROM users WHERE Email='$Email' and Password='$Password'";
$result=mysqli_query($mysqli, $sqli);

//Mysql_num_row is counting table row
$count=mysqli_num_rows($result);



// If result matched $Email and $Password, table row must be 1 row
if($count==1){

//redirect to file "menu.html"

header("location:menu.html");
}
//If all else fails they shall not pass!
else {
echo "Wrong Email or Password. YOU SHALL NOT PASS!";
}
?>

3 个答案:

答案 0 :(得分:1)

要从数据库中的表格中获取ID,请使用 mysqli_fetch_array mysqli_fetch_assoc

将此插入 $ result

下方
while($row = mysqli_fetch_array($result)): //fetching the row from database

   $id = $row['id']; //the id column in your table
   $_SESSION['id'] = $id; //the id is now saved in your session for future use

endwhile;

在另一个页面中,不要忘记 session_start(); 来访问$ _SESSION ['id'],以便您可以从数据库中的表中访问与该id相关联的不同信息。 / p>

答案 1 :(得分:0)

if ($count == 1) {
    //redirect to file "menu.html" 
    While ($row = mysql_fetch_array($result)) {
        $userName = $row['username']; // Where username is the user ID value in your db
        $_SESSION['username'] = $userName;
        header("location:menu.html");
    }
}

答案 2 :(得分:0)

好的,您需要做的是从数据库中获取用户ID。假设users表有一个名为id的列:

$result=mysqli_query($mysqli, $sqli);

//Mysql_num_row is counting table row
$count=mysqli_num_rows($result);

// If result matched $Email and $Password, table row must be 1 row
if($count==1){

    $row = mysql_fetch_array($result);
    $_SESSION['userID']=$row['id'];

    header("location:menu.html");
    die();
}

请注意,mysql_fetch_array通常在while循环中调用,以获取多行。但是在这里你只有一行,所以不需要