問題描述
就在最近,我在 PHP/MySQL 中改用 PDO 并轉換了幾十個查詢.他們中的大多數都有效,但是這個非常簡單的方法會在 $sql->execute()
$sql=$pdo->prepare("SELECT id FROM user WHERE username = :username LIMIT 1");$sql->execute(array(':username',$username));
<塊引用>
PDOStatement::execute() pdostatement.execute SQLSTATE[HY093]:無效的參數號:綁定變量的數量與......中的標記數量不匹配
經過研究,我找到了這個鏈接:https://bugs.php.net/bug.php?id=60515
... 因此嘗試將查詢更改為
$sql=$pdo->prepare("SELECT `id` FROM `user` WHERE `username` = :username LIMIT 1");$sql->execute(array(':username',$username));
但結果還是一樣.有沒有人看到明顯錯誤的地方,或者為什么這個查詢在所有其他人都這樣做時不起作用?
在此先非常感謝您!
':username',$username
僅適用于 bindParam() 方法:
$sql->bindParam(':username', $username, PDO::PARAM_STR);
看看這里:http://www.php.net/手冊/en/pdostatement.bindparam.php
對于執行,您需要傳遞正確的僅輸入值數組:
$sql->execute(array(':username' => $username));
占位符:
你也可以使用這個:
$sql->execute(array($username));
但為此,您需要將查詢更改為:
$sql=$pdo->prepare("SELECT `id` FROM `user` WHERE `username` = ?LIMIT 1");
?用作占位符并從數組中獲取變量.當您在 SQL 語句中使用更多占位符時,該函數會按順序從數組中取出所有變量.
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 $sql->execute()
$sql=$pdo->prepare("SELECT id FROM user WHERE username = :username LIMIT 1");
$sql->execute(array(':username',$username));
PDOStatement::execute() pdostatement.execute SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in ...
After research, I found this link: https://bugs.php.net/bug.php?id=60515
... and therefore tried to change the query to
$sql=$pdo->prepare("SELECT `id` FROM `user` WHERE `username` = :username LIMIT 1");
$sql->execute(array(':username',$username));
But still with the same result. Does anybody see what is obviously wrong or why does this query not work when all others did?
Thank you very much in advance!
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.
這篇關于PDO - 無效的參數號的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!