0

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
Ross
  • 3
  • 2
  • 1
    what do you see when you `print_r($results);` before the loop? – Zak May 28 '19 at 20:56
  • PDOStatement Object ( [queryString] => SELECT username FROM users WHERE user_id="$userid" ) – Ross May 28 '19 at 20:58
  • https://www.php.net/manual/en/pdostatement.fetchall.php – AbraCadaver May 28 '19 at 21:04
  • I'd suggest you check the values you're using for the `$userid` parameter. Seems like the ID doesn't exist, hence the `$results` are blank and `$username` never gets initialized, causing the error – Hamman Samuel May 28 '19 at 21:11

1 Answers1

3

You can't directly use variables within string with single quotes ':

$foo = 'bar';
echo "hello $foo"; // hello bar
echo 'hello $foo'; // hello $foo

Which lead to your query searching for a user id equalling the string $suserid, as there is no possible result, your foreach loop runs 0 laps and $username is never defined.


But using double quotes " would make your query vulnerable to SQL injection. You are already using a prepared statement but in a wrong way.
Working solution with named parameters:

$results = $pdo->prepare('SELECT username FROM users WHERE user_id = :id');
$results->bindParam(':id', $userid, PDO::PARAM_INT);
$results->execute();

See PDOStatement::bindParam().


You also forgot to use fetch() (not fetchAll() as you're searching a username based on a primary key. As a primary key is unique, you can only get 1 row maximum. Therefore, no need for a loop):

$results->execute();

$username = $results->fetch();

return $username;
AymDev
  • 6,626
  • 4
  • 29
  • 52