在mysqli查询中使用会话用户名为“WHERE”[关闭]

I know I am doing something wrong but I really would like to know what it is. I can echo the username of the session loggedin user using <?php echo $_SESSION['username']; ?>but I don't know why it doesn't work when I try to query database using the same technique. my codes below

I include this in the page

<?php session_start(); $username=$_SESSION['username']; ?>

and here is the code that was suppose to display firstname and user_id of the sessions logged in user

    <?php
$conn = new mysqli('localhost', 'root', 'browser', 'test');

if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

$username = '$username';

$sql = "SELECT `user_id`, `firstname` FROM `members` WHERE `username`='$username'"; 
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    echo '<br /> user_id: '. $row['user_id']. ' - firstname: '. $row['firstname'];
  }
}
else {
  echo '0 results';
}

$conn->close();
?>
$username = '$username';

PHP variables inside single-quotes are not expanded. So now your variable is the literal string '$username', which undoubtedly won't match any user in your database.

You probably need to set $username = $_SESSION['username']; in your second PHP script.