2016-01-08 42 views
1

同时插入新的数据到数据库警告:PDOStatement对象::执行():SQLSTATE [HY093]

警告我都遇到过这样的错误:PDOStatement对象::执行():SQLSTATE [HY093]:无效参数 号:

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; 
} 
:绑定变量的数目不 /opt/lampp/htdocs/projectclasses/DB.php在线47上

的方法的代码匹配的令牌数3210

插入的代码:

$user = DB::getInstance()->insert('users', array(
    'username' => 'Marco', 
    'password' => '123456', 
    'salt' => 'salt' 
)); 
+0

echo你的$ sql变量,你看到了什么? – Clay

+0

INSERT INTO users('username','password','salt')VALUES(?,?,?) –

回答

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

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

+0

谢谢克莱顿我真的很感激你 –

相关问题