Search code examples
phpmysqliprepared-statement

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

  • 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=?');