如何使用客户ID进行新会话? PHP / MySQL

时间:2018-12-29 05:06:08

标签: php sql

我有一个登录页面,该页面生成$ _SESSION ['username'] = $ username。 我想创建新的会话$ _SESSION ['id'],该会话存储客户的ID而不是用户名,并将其传递给另一个页面。 我仍在学习,因此请使您的答案易于理解。谢谢

这是我的登录代码

<?php
    require('dbConfig.php');

     session_start();
   if(!empty($_SESSION["username"])){ 
    header("LOCATION:index.php");
  }


    if (isset($_POST['username'])){

    $username = stripslashes($_REQUEST['username']); // removes backslashes
    $username = mysqli_real_escape_string($db,$username); //escapes special 
    characters in a string
    $password = stripslashes($_REQUEST['password']);
    $password = mysqli_real_escape_string($db,$password);


        $query = "SELECT * FROM `members` WHERE username='$username' and password='".md5($password)."'";
    $result = mysqli_query($db,$query) or die(mysql_error());
    $rows = mysqli_num_rows($result);
        if($rows==1){
      $_SESSION['username'] = $username;

      header("Location: index.php"); 
            }else{
        echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
        }
    }else{
?>

2 个答案:

答案 0 :(得分:1)

确保每个页面都存在session_start()并将其添加到代码的会话创建部分:

$_SESSION['id'] = $result['id'];

$_SESSION['username'] = $username;

我假设您的表中的“ id”被称为“ id”

您可以使用

echo "<pre>";
print_r($_SESSION);
echo "</pre>";

要查看会话中的内容

答案 1 :(得分:0)

首先:尝试使用mysqli_prepare来查询用户,方法是将变量直接传递到SQL代码中,然后将系统打开到SQL Injection。

  $query = "SELECT * FROM `members` WHERE username=? and password=?"
  $password = md5($password);
  $statement = mysqli_prepare($db, $query);

  mysqli_stmt_bind_param($statement, 'ss', $username, $password); //bind variables before execute sql command to prevent SQL injection.
  mysqli_stmt_execute($statement);
  $result = mysqli_stmt_get_result($statement);

  $rows = mysqli_stmt_affected_rows($statement);
  if($rows==1){
     $user = mysqli_fetch_array($result, MYSQLI_ASSOC)
     $_SESSION['username'] = $username;
     $_SESSION['id'] = $user['id'];
     header("Location: index.php"); 
  }

此外,您必须在session_start();中包含index.php才能在index.php页上读取SESSION变量。