2013-06-25 72 views
-1

我遇到了一個問題,即使用PDO將數據插入到我的數據庫中,因爲正在輸入錯誤的結果。帶有數組的PHP PDO插入

類的工作原理如下:

class PDOMySql{ 
public function connect(){ 
      try{ 
       $dbh = new PDO('mysql:host='.$this->server.';dbname='.$this->database,$this->username,$this->password); 
       $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); 
       if(!$dbh){ 
        throw new Exception('Error Connecting to Server'); 
       } 
       return $dbh; 

      } catch(Exception $e){ 
        if(MAILING == "ON"){ 
         $this->report->mailing($e); 
        } 
        else{ 
         throw $e; 
        } 
      } 
     } 

public function insert($query,$values,$dbh){ 
     try{ 
      if(!is_array($values)){ 
       throw new Exception("Values must be in array format: e.g: array('a','b','c')"); 
      } 
      $a = substr_count($query,'?'); 
      $b = count($values); 
      if($a != $b){ 
       throw new Exception("Number of values must match the number of placements"); 
      } 
      $prepare = $dbh->prepare($query); 
      $i = 1; 
      foreach($values as $item){ 
       $type = strtolower(gettype($item)); 
       if($type == "null"){ 
        $param = PDO::PARAM_NULL; 
       } 
       elseif($type == "string"){ 
        $param = PDO::PARAM_STR; 
       } 
       elseif($type == "integer"){ 
        $param = PDO::PARAM_INT; 
       } 
       else{ 
        throw new Exception("Type: PDO::PARAM_".$type. " Not currently supported"); 
       } 
        $prepare->bindParam($i, $item, $param); 
       $i++; 
      } 

      $prepare->execute(); 
      $lastId = $dbh->lastInsertId();    
      return $lastId; 

     } catch(Exception $e){ 
      throw $e; 
     } 

    } 

} 

當類被稱爲是這樣的:是

$db = new MySql(); $con = $db->connect(); 
$sql = "INSERT INTO users (a,b,c,d) VALUES (?,?,?,?)"; 
$values = array("1st column", "2nd column",null,"asdfasd"); 
$a = $db->insert($sql,$values,$con); 

插入值如下: 一個:第一列。 b:第二列。 c:第二列。 d:asdfasd。

正如你所看到的,而不是輸入null,第二個值被放入c列。

是否有更簡單的方法來插入動態創建的值,因爲有些可能爲null,並且使用此方法似乎忽略空值並使用最後一個值。有人知道爲什麼會發生這種情況,或者有更簡單的方法來解決這個問題嗎?

+0

這聽起來像一個錯誤。如果您的PHP和PDO版本存在已知問題,請檢查PHP錯誤跟蹤器。 – hakre

+0

如果不是傳遞'null',而是傳遞字符串'null''。 – nickb

+0

嘗試了它並編輯它來添加它,但有人編輯它並刪除了編輯 –

回答

0

我會建議使用bindValue()而不是bindParam()。

http://php.net/manual/en/pdostatement.bindvalue.php

$prepare->bindValue($i, $item, $param); 

然而,它被認爲是不好的做法,有這麼多的匿名值(?,?,?,?) ......你應該使用佔位符,如果他們是從$ _POST陣列去,你可以在的foreach $ _ POST數組並使用這些鍵作爲佔位符

+0

我已經更改了代碼使用數組和鍵,並將我的foreach更改爲foreach($ value as $ key => $ item),然後使用bindValue (':'。$ key。',$ item,PDO :: PARAM_STR); –