2016-01-08 40 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

謝謝克萊頓我真的很感激你 –

相關問題