【发布时间】:2016-04-12 15:47:33
【问题描述】:
我在向数据库插入新数据时遇到了这个错误
警告:PDOStatement::execute(): SQLSTATE[HY093]: 无效参数 number:绑定变量的数量与中的标记数量不匹配 /opt/lampp/htdocs/projectclasses/DB.php 第 47 行
方法代码:
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'
));
【问题讨论】:
-
回显你的 $sql 变量,你看到了什么?
-
插入用户 (
username,password,salt) 值 (?, ?, ?)