2013-10-25 74 views
-2

在PHP中,我想執行一個SQL查詢,將SQL數組值與SQL語句一起傳遞。我無法做到這一點。帶有SQL語句的PHP數組值

請考慮以下

$db = "mydatabase.sqlite"; 
$array = array(
       "key1" => "value1", 
       "key2" => "value2", 
       "key3" => "value3" 
     ); 

try { 

    $dbhandle = new PDO("sqlite:$db"); 
    $dbhandle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    foreach ($array as $item) { 

     $timestamp = 
     $dbhandle->exec(
       "INSERT OR REPLACE INTO table (field1, field2, field3) 
        VALUES ('$item['key1']', '$item['key2']', '$item['key3']')" 
      ); 
     $dbhandle = NULL; 

    } 

    } 

catch(PDOException $e) { 
    print "Exception : ".$e->getMessage()."\n"; 
    } 

如何表達的SQL語句?

回答

1

當插值數組元素連接成一個字符串,不要把引號圍繞重點:

  "INSERT OR REPLACE INTO table (field1, field2, field3) 
       VALUES ('$item[key1]', '$item[key2]', '$item[key3]')" 

,或者使用「複雜」的語法與花括號:

  "INSERT OR REPLACE INTO table (field1, field2, field3) 
       VALUES ('{$item['key1']}', '{$item['key2']}', '{$item['key3']}')" 

然而,這將更好地使用準備好的語句:

$stmt = $dbhandle->prepare("INSERT OR REPLACE INTO table (field1, field2, field3) 
          VALUES (:key1, :key2, :key3)"); 
$stmt->execute($item); 
+0

技術上正確,但@CptNemo請使用預處理語句;使用例如'$ pdoStmt-> bindValue(':key1',$ item ['key1'])'在尊重DB數據類型的同時轉義輸入,並且您可以使用默認數組表示法... – feeela