【问题标题】:Warning: PDOStatement::execute(): SQLSTATE[HY093]警告:PDOStatement::execute(): SQLSTATE[HY093]
【发布时间】: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) 值 (?, ?, ?)

标签: php mysql pdo


【解决方案1】:

Execute 可以接受参数数组,而不是单独绑定它们。

所以,首先,删除这个:

    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));
?>

来源: http://php.net/manual/en/pdostatement.execute.php

【讨论】:

  • 谢谢克莱顿,我真的很感激你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多