2010-09-29 97 views
0

我想向INSERT語句添加另一個值,但無論我做什麼,它都會導致各種錯誤。有人能告訴我正確的方式來編碼嗎?爲數據庫查詢添加值

我原來的工作代碼是這樣的:

$sql = "INSERT INTO `act` (`department`) VALUES ('". implode("'),('", $dept) . "')"; 

我曾嘗試在其他之中:

$sql = "INSERT INTO `act` (`department`,`item`) VALUES ('". implode("'),('", $dept) . "','". implode("'),('", $box) . "')"; 

也許我應該張貼我的代碼生成結果:

$dept = array(); 
$box = array(); 

while ($row = mysql_fetch_array($result)) { 
      $dept[] = $row['department']; 
      $box[] = $row['custref']; 
} 

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); 
header("Cache-Control: no-cache, must-revalidate"); 
header("Pragma: no-cache"); 
header("Content-type: application/json"); 
$json = ""; 
$json .= "{\n"; 
$json .= "dept: [\"". implode('","', $dept). "\"],\n"; 
$json .= "box: [\"". implode('","', $box) ."\"]\n"; 
$json .= "}\n"; 
echo $json; 

$sql = "INSERT INTO `act` (`department`) VALUES ('". implode("'),('", $dept) . "')"; 
$result = runSQL($sql); 

回答

0

多插入應該是我n中的格式:

INSERT INTO `act` (`department`, `item`) VALUES ('dept1', 'item1'), ('dept2', 'item2'), ('dept1', 'item1'), ('dept3', 'item3');, 

$insert = array(); 
for ($i=0; $i<sizeof($dept); $i++) { 
    $insert[] = '(\'' . $dept[$i] . '\',\'' . $box[$i] . '\')'; 
} 

$sql = "INSERT INTO `act` (`department`,`item`) VALUES " . implode(',', $insert); 
+0

該代碼正在與1個項目的基礎上,是有辦法只包含另一個字段,在我的例子不造成錯誤?謝謝 – 2010-09-29 10:57:42

+0

@ Mr.Putersmit:'$ dept'和'$ box'的格式是什麼? – Matt 2010-09-29 11:10:20

+0

Matt。 VARCHAR。如果它幫助我發佈上面的代碼。感謝 – 2010-09-29 11:20:12

1

你可以嘗試這樣的事情

$sql="INSERT INTO `act` 
     (`department`,`box`) 
     VALUES 
    "; 

foreach($dept as $index => $value) 
{ 
    $sql.=" 
     (
      '".mysql_real_escape_string($value)."', 
      '".mysql_real_escape_string($box[$index])."' 
     ),"; 
} 

$sql=rtrim($sql,',') ; 
$result = runSQL($sql); 
+0

+1的正確轉義 – knittl 2011-06-27 09:18:42