I'm attempting to create a PHP function that will allow me to convert a user_id to username from my MySQL database (as the assignment i'm working on requires this to be done a lot so i'd rather just call a function to quickly do this instead of repeating myself)
The issue i'm having is I can't assign the value returned from my query to a variable which is causing an undefined variable error.
The function is being called from a different .php script so I need the value to be returned. The user_id is passed along as a parameter when the function is called.
I've attempted already declaring the variable before the query and assigning the value during the foreach loop but I cannot get the values to save and return.
//Convert user_id to Username
function usernameConvert($userid)
{
//Connection to DB
include '../dbconnect.php';
$results = $pdo->prepare('SELECT username FROM users WHERE
user_id="$userid"');
$results -> execute();
foreach ($results as $row)
{
$username = $row["username"];
}
//comes back undefined
return $username;
}
The main error i'm getting is it's an undefined variable.
Thanks in advance.