PDO-无效的参数号 [英] PDO - Invalid parameter number

查看:73
本文介绍了PDO-无效的参数号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我已经切换到在PHP/MySQL中使用PDO并转换了数十个查询.他们中的大多数人都可以工作,但是这个非常容易的人在$sql->execute()

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]:无效的参数编号:绑定变量的数量与...中的标记数量不匹配.

PDOStatement::execute() pdostatement.execute SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in ...

经过研究,我找到了以下链接: https://bugs.php.net/bug.php?id = 60515

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?

非常感谢您!

推荐答案

':username',$username仅在bindParam()方法中有效:

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

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

在这里看看: http://www.php.net/manual/zh-TW/pdostatement.bindparam.php

要执行,您需要传递正确的仅输入值数组:

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

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

占位符:

您也可以使用此:

$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");    

?作为palceholder并从数组中获取变量.当您在SQL语句中使用更多占位符时,该函数将按顺序从数组中取出所有变量.

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-无效的参数号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆