Create getUserName() function
a. Open database
b. Search table for “user_id” session variable if it exists
c. Return “user_name” or “not logged in???”
I don’t know how you have your application structured, so I don’t know where to suggest you put your code, but I see from a previous post that you are using (or looking into using) PDO. I also don’t know how your database table is set up, so this is just an example.
You need to write a query to the database something like this:
"SELECT first_name, last_name FROM users WHERE id = " . $_SESSION['user_id'];
Then you can assign your user’s name to a variable and echo it.
The function loggedInUsername was defined as taking a parameter $row. But when you called the function in your last bit of code, you didn’t pass this parameter through. Also, you didn’t return a value in that function (which should have been $row), so there would be nothing to echo.
Try removing the parameter $row from the function definition, and put it inside like this:
<?php
function loggedInUsername() {
require_once'connect.php';
$sql= "SELECT username FROM users WHERE id = " . $_SESSION['user_id'];
$stmt = $pdo->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row;
}
?>
And as you’ve gone to the trouble of using PDO for your query, have a look at prepared statements rather than just appending the session variable to the query string:
function loggedInUsername() {
require_once 'connect.php';
$sql = "select username from users where id = :id";
$prep = $pdo->prepare($sql); // prepare the query
$prep->bindParam(':id', $_SESSION['user_id']); // assign the parameter
$result = $prep->execute(); // execute the query
$username = $prep->fetchColumn(); // only one column produced by query
return $username;
}
$user = loggedInUsername();
echo $user;
It’s a good habit to get into, while it won’t make a massive amount of difference to this specific operation.
Another thing you need in that function, though, is some code to deal with what happens if the user_id isn’t found in your users table. Probably return false in that case, and deal with that result when you call it.