gpt4 book ai didi

php - 警告:mysqli::bind_param():变量数与动态分配变量时准备语句中的参数数不匹配

转载 作者:行者123 更新时间:2023-11-28 23:26:55 26 4
gpt4 key购买 nike

我目前正在寻找使用 API 安全连接和管理查询(SQL 注入(inject)缓解)的方法,同时尝试遵循 DRY 准则。我使用准备好的语句来防止 SQL 注入(inject),但在运行收到 HTTP GET 请求时调用的函数时遇到警告:

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

然后我的查询失败了:

Error: Commands out of sync; you can't run this command now Errno 2014

一个简单的谷歌搜索为我提供了这个答案:

If you get Commands out of sync; you can't run this command now in your client code, you are calling client functions in the wrong order.

只有当数组中有多个参数时才会出现警告和错误消息。我的mySQL查询函数如下:

    //set properties to values given by constructor params, 
//open mysqli connection, etc..

public function query_db_stmt($sql, $param)
{

$stmt = $this->connection->prepare($sql);
for ($i = 1; $i < count($param); ++$i)
{
$stmt->bind_param(($param[0][$i - 1]), $param[$i]);
}

$stmt->execute();

$result = $stmt->get_result();

$stmt->close();
return $result;
} // do other stuff here, like close the sql connection in __destruct()...

然后我创建对象,然后像这样调用查询函数:

$sql = 'SELECT ? FROM user WHERE id=?;';
$result = $mysql_db->query_db_stmt($sql, array('si', '*', $this->args[0]));

我显然做错了什么,因为我收到了这些警告和错误编号 2014,但我无法弄清楚它是什么。任何帮助将不胜感激。

编辑:

我现在明白我不能将列名或表名用作准备好的语句,但是在使用此代码时我仍然遇到类似的问题,除了 HTTP PUT 请求:

    parse_str(file_get_contents("php://input"), $put_vars);
$sql = 'INSERT INTO user (username, password, email, birth, sex) VALUES (?, ?, ?, ?, ?);';
$mysql_db->query_db_stmt($sql, array('sssss', $put_vars['username'], password_hash($put_vars['password'], PASSWORD_DEFAULT),
$put_vars['email'], $put_vars['birth'], $put_vars['sex']));

使用 curl,我运行 curl -X PUT http://localhost/r.php -d username=foo -d password=boo -d email=test@gmail.com -d birthday=2015-08-13 -d sex=m

同样的错误出现了 5 次:

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

和以前一样,但没有数据库查询失败错误。有什么意见吗?

最佳答案

问题是您试图在 PDO 中绑定(bind)表名。表名和列名在 PDO 中不能被替换。

关于php - 警告:mysqli::bind_param():变量数与动态分配变量时准备语句中的参数数不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38939091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com