PDO - Invalid parameter number

后端 未结 2 1964
生来不讨喜
生来不讨喜 2020-12-11 16:28

Just recently I\'ve switched to using PDO in PHP/MySQL and transformed some dozens of queries. Most of them worked, however this very easy one throws an exception at $

相关标签:
2条回答
  • 2020-12-11 16:56

    The ':username',$username works only in bindParam() method:

    $sql->bindParam(':username', $username, PDO::PARAM_STR);
    

    Take a look here: http://www.php.net/manual/en/pdostatement.bindparam.php

    For execute you need to pass a correct array of input-only values:

    $sql->execute(array(':username' => $username));
    

    Placeholder:

    You can also use this:

    $sql->execute(array($username));
    

    But for this you need to change your query to this:

    $sql=$pdo->prepare("SELECT `id` FROM `user` WHERE `username` = ? LIMIT 1");    
    

    The ? works as palceholder and take the variables from the array. When you use more placeholder in your SQL statement the function takes all the variables out of the array in it's order.

    0 讨论(0)
  • 2020-12-11 17:03

    This is not bug, you provide two parameters for only one placeholder.

    $sql->execute(array(':username',$username));
    

    should be

    $sql->execute(array(':username' => $username));
    
    0 讨论(0)
提交回复
热议问题