That’s actually a very good question that has almost no good answers on Stack Overflow.
Basically you need the following steps to perform a SELECT query using mysqli:
- create a correct SQL SELECT statement and replace all variables in the query with with question marks (called placeholders or parameters)
- Prepare the resulting query
- Bind all variables to the previously prepared statement
- Execute the statement
- get the mysqli result variable from the statement.
- fetch your data
The detailed explanation can be found in my article, How to run a SELECT query using Mysqli, as well a helper function to simplify the routine.
Following this plan here is your code
$sql = "SELECT * FROM users WHERE id=?"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $id);
$Stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch the data
now you can store the username in the session variable:
$_SESSION['name'] = $user['name'];