2012-02-03 48 views
0

我試圖將數組中的數據行插入到表中。它是將這個而不是實際的數據:使用for循環將數組的實例插入到表中

enter image description here

這裏是我的代碼:

for ($i = 0; $i < $arraycount; $i++) 
{ 
    $db->query("INSERT INTO contact_tariffs (qid, retail_name, tariff_name, tariff_net, tariff_rental, tariff_inclusive, tariff_length, tariff_data) 
       Values ('$qid', '$quote->retail_name[$i]', '$quote->tariff_name[$i]', '$quote->tariff_net[$i]', '$quote->tariff_rental[$i]', '$quote->tariff_inclusive[$i]', '$quote->tariff_length[$i]', '$quote->tariff_data[$i]')");       
} 

我一直在使用$_POST$_SESSION變量和我有唯一的解決辦法是,當有類似的問題臨時將這些值傳輸到臨時變量並使用臨時變量插入到數據庫中。

+0

看看[字符串解析](http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing),使用大括號,或者可能使用sprintf或準備好的陳述 – Wrikken 2012-02-03 11:44:27

回答

2

變量太複雜,無法在字符串中使用。 PHP將$quote->retail_name解釋爲一個變量,$i解釋另一個變量,因爲它不知道一個變量的結束位置和另一個變量的起始位置。例如:

$i = 1; 
$quote->retail_name[ 1 ] = 'foo'; 

echo "result: $quote->retail_name[$i]"; // --> result: Array[1] 
// the above is the same as 
// echo $quote->retail_name; echo "["; echo $i; echo "]; 

echo "result: ".$quote->retail_name[$i]; // --> result: foo 
// The above leaves the variable outside the string so it's parsed correctly. 
// You could also use "result: {$quote->retail_name[$i]}" 

http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

見試試這個:

for ($i = 0; $i < $arraycount; $i++) 
{ 
    $db->query("INSERT INTO contact_tariffs (qid, retail_name, tariff_name, tariff_net, tariff_rental, tariff_inclusive, tariff_length, tariff_data) 
       Values ('$qid', '".$quote->retail_name[$i]."', '".$quote->tariff_name[$i]."', '".$quote->tariff_net[$i]."', '".$quote->tariff_rental[$i]."', '".$quote->tariff_inclusive[$i]."', '".$quote->tariff_length[$i]."', '".$quote->tariff_data[$i]."')");       
} 

雖然應該逃避值也是如此。像PDO的東西會更好。

+0

+1指向PDO,或者他可以使用語法:'''{$ quote-> retail_name [$ i]}'「' – Vyktor 2012-02-03 11:49:40

+0

我不明白你的意思是太複雜,你是指變量結構或裏面的數據呢? – kaleeway 2012-02-03 11:51:47

+0

PHP沒有意識到'$ quote-> whatever [$ i]'應該是一個變量。它認爲它分別是'$ quote-> whatever'和'$ i'。查看編輯。 – JJJ 2012-02-03 12:03:11

1

你可以使用大括號,插入數組值直接進入一個雙引號的字符串:

for ($i = 0; $i < $arraycount; $i++) 
{ 
    $db->query("INSERT INTO contact_tariffs (qid, retail_name, tariff_name, tariff_net, tariff_rental, tariff_inclusive, tariff_length, tariff_data) 
       Values ('{$qid}', '{$quote->retail_name[$i]}', '{$quote->tariff_name[$i]}', '{$quote->tariff_net[$i]}', '{$quote->tariff_rental[$i]}', '{$quote->tariff_inclusive[$i]}', '{$quote->tariff_length[$i]}', '{$quote->tariff_data[$i]}')");       
} 

...並請注意SQL注射。

+0

它在一個值得信賴的系統,所以我不擔心:) – kaleeway 2012-02-03 11:52:23

+0

正確地轉義SQL查詢中的參數不僅僅是爲了防止惡意注入。 「奧尼爾」等完美有效的名字也可能讓你陷入困境。所以,不管你是否信任所有用戶(和/或即使你自己是唯一的用戶),也要逃避那些該死的事情。 – Wrikken 2012-02-03 12:00:19

相關問題