无法在php中检索登录用户的ID

时间:2017-12-12 23:55:00

标签: php mysql

我发现很难检索登录用户的id(来自mysql数据库中的记录表)。我尝试了下面的功能来检索它,但是不起作用。

<?php
    $password = md5($password);
    $sql = "select * from users where username = '$username'";
    $result = mysqli_query($conn, $sql);
    $count = mysqli_num_rows($result);
    $row = mysqli_fetch_assoc($result);

    if($count==1 && $row['password'] == $password){
         $_SESSION['username'] = $row['username'];
         header('location: loggedin.php');
    }else{
         $errorMsg = 'Invalid Username or Password';
    }

这就是我想要实现的目标。

 $user_id = userid(id,username);



function userid(id,username)
{
    $sql = "select id from users where username =  $_SESSION['username']"
    $result = mysqli_query($conn, $sql);
}


?>

1 个答案:

答案 0 :(得分:0)

您必须考虑以下因素:

  • 调用函数的方式,必须将声明的变量作为参数
  • 您的函数
  • 中没有return
  • 您在宣布;变量
  • 时忘记了分号($sql

您可以使用数据库连接替换id参数:

function userid($dbcon, $username)
{
    $stmt = $dbcon->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($id);
    $stmt->fetch();
    $stmt->close();

    return $id;
}

然后,调用函数:

/** HOPE YOU DECLARED SOMEWHERE YOUR DATABASE CONNECTION PRIOR TO YOUR FUNCTION CALL **/
$username = $_SESSION['username']; /** JUST REPLACE THIS WITH ANY DATA YOU WANT **/

$user_id = userid($dbcon, $username);

困扰我的是,为什么将username用户存储在会话变量中而不是id?如果用户在登录时更改了用户名,该怎么办?