我在将新数据插入数据库时遇到此错误
警告:PDOStatement :: execute():SQLSTATE [HY093]:参数无效 number:绑定变量的数量与令牌的数量不匹配 第47行/opt/lampp/htdocs/projectclasses/DB.php
方法代码:
public function query($sql, $params = array())
{
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
if(count($params))
{
foreach($params as $param)
{
$x = 1;
$this->_query->bindParam($x, $param);
$x++;
}
}
if($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else
{
$this->_error = true;
}
}
return $this;
}
public function insert($table, $fields = array())
{
if(count($fields))
{
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field)
{
$values .= "?";
if($x < count($fields))
{
$values .= ", ";
}
$x++;
}
$sql = "INSERT INTO users (`". implode('` ,`', $keys) ."`) VALUES (".$values.")";
if(!$this->query($sql, $fields)->error())
{
return true;
}
}
return false;
}
插入代码:
$user = DB::getInstance()->insert('users', array(
'username' => 'Marco',
'password' => '123456',
'salt' => 'salt'
));
答案 0 :(得分:0)
执行可以接受一系列参数,而不是单独绑定它们。
所以,首先,删除它:
if(count($params))
{
foreach($params as $param)
{
$x = 1;
$this->_query->bindParam($x, $param);
$x++;
}
}
你可能需要使用array_values使它像这样一个真正的数组(如果你的数组有键,那么它将尝试使用键绑定):
if($this->_query->execute(array_values($params)))
这是PHP文档中的一个例子:
<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
?>