2012-03-09 113 views
4

我剛剛開始準備語句的工作,我的第幾個例子摸索出偉大的,但現在我運行到一個SQL語法,我不明白。我有一個函數執行一個INSERT,採用關聯數組的參數,其中數組的鍵是字段,數組的值是要插入的值。例如:語法錯誤與PDO預處理語句

$arr = array("field1" => "value1", 
      "field2" => "value2"); 

$this->insert("table", $arr); 

將執行:

INSERT INTO table ('field1', 'field2') VALUES ('value1', 'value2') 

然而,試圖做到這一點的時候,我得到以下錯誤:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''post_title', 'post_body') VALUES ('Testing!', '1 2 3!')' at line 1

這是我的函數:

/** 
    * insert() 
    * 
    * Performs an insert query 
    * 
    * @param string $table The table to be inserted into 
    * @param array $fields An associative array of the fields to be inserted 
    *       and their respective values 
    * @return void 
    * 
    */ 
    function insert($table, $fields) { 
     if (empty($table) || empty($fields)) { 
      trigger_error('insert(): one or more missing parameters', E_USER_ERROR); 
     } 

     if (!is_array($fields)) { 
      trigger_error('insert(): second parameter expected to be array', E_USER_ERROR); 
     } 

     for ($i = 0; $i < count($fields); $i++) { 
      $mark[] = "?"; 
     } 
    //(?, ?, ...) 
    $mark = "(" . implode(", ", $mark) . ")"; 

    $bind = array_merge(array_keys($fields), array_values($fields)); 

    //INSERT INTO table (?, ?, ...) VALUES (?, ?, ...) 
    $query = 'INSERT INTO '.$table.' '.$mark.' VALUES '.$mark; 

    //Prepare and execute 
    $stmt = $this->connection->prepare($query); 
    var_dump($stmt); 
    var_dump($bind); 
    $stmt->execute($bind); 
} 

我與調用它:

$this->insert('post', array("post_title"=>"Testing!", "post_body"=>"1 2 3!")); 

而且,這兩個的var_dump()s的最終結果:

object(PDOStatement)[7] 
public 'queryString' => string 'INSERT INTO post (?, ?) VALUES (?, ?)' (length=37) 

array 
    0 => string 'post_title' (length=10) 
    1 => string 'post_body' (length=9) 
    2 => string 'Testing!' (length=8) 
    3 => string '1 2 3!' (length=6) 

我可能是錯的,但據我所知,沒有辦法檢查實際查詢被送到服務器,所以我真的不知道SQL語法來自哪裏。如果有人能指出什麼是錯的,我將非常感激。

+0

查詢中的表名稱在哪裏? – PeeHaa 2012-03-09 19:56:31

+1

你不能指定這樣的字段名稱。顯式字段名不是字符串或整數,它們是標識符。如果你是_really_肯定列名,第一個'$ mark'可能是'破滅(「」,array_keys($字段);'我還是白名單的字段名... – Wrikken 2012-03-09 19:59:31

+1

另外:記住PDO _emulates_準備/在一定條件下的發言,除非另行告知。 – Wrikken 2012-03-09 20:01:19

回答

6

您不能綁定標識符。所有志願者PDO福音傳教士都不知道的事情。

你必須使用ol'good查詢構建添加標識符。

讓他們列入白名單,使字段名條款指出,名單

Insert/update helper function using PDO的完整實現。

+0

你說得對,我剛剛更換用的?標記實際的字段名稱,現在就起作用了,現在我需要牢記這一點! – 2012-03-09 20:10:12

0

字段名應與蜱(``)沒有引號('')被surronded。它應該是

INSERT INTO (`field1`, `field2`) VALUES ('value1', 'value2') 
0

在您的SQL查詢:

INSERT INTO ('field1', 'field2') VALUES ('value1', 'value2') 

你忘了表名:

INSERT INTO table('field1', 'field2') VALUES ('value1', 'value2'); 
+0

對不起,那是一個錯字,在底部的var_dump你應該看到,我沒有包含表名。 – 2012-03-09 20:00:29