'Unsure why I am getting: Number of variables doesn't match number of parameters in prepared statement

I am trying to do a simple test but am experiencing errors. I am trying to add the parameters and I have done some research, none of which has helped me understand where I have gone wrong.

I have already tried looking on the PHP website and Stackoverflow. This is for a test project.

$stmt = $con->prepare('SELECT username, rank, id, steamid, avatar FROM users WHERE id="$uid"');

$stmt->bind_param('i', $uid);
$stmt->execute();
$stmt->bind_result($username, $rank, $id, $steamid, $avatar);
$stmt->fetch();
$stmt->close();

My expected result is for it to select only the rows specified with the "WHERE" call. My actual result is this error:

mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement



Solution 1:[1]

You are binding one variable, but you have zero parameters in your prepared statement. Interpolating a PHP variable into a string is not a parameter.

WRONG: Zero parameters, just string interpolation:

$stmt = $con->prepare('SELECT username, rank, id, steamid, avatar FROM users 
  WHERE id="$uid"');

RIGHT: One parameter:

$stmt = $con->prepare('SELECT username, rank, id, steamid, avatar FROM users
  WHERE id=?');

Solution 2:[2]

You get error because you don't use column name = ? in the prepared statement. Then using bind_param you bind values to parameters, set parameters and execute.

$stmt = $con->prepare('SELECT username, rank, id, steamid, avatar FROM users WHERE id = ?');

$stmt->bind_param('i', $uid);
//set parameters and execute
$uid = 'value here';
$stmt->execute();

$stmt->close();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bill Karwin
Solution 2