我有以下html提交表單。這個表單是一個PHP_SELF,並將輸入數據作爲一個數組存儲在$ _POST中。
<html>
<body>
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<fieldset>
<legend>Direct Bill Information:</legend>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" />
</fieldset>
<input type="submit" value="submit" name="submit" />
</form>
</body>
</html>
我有了字段「db_num」和「db_amnt」一個MySQL表,我想插入陣列到表中的所有輸入數據。我環顧四周,'內爆'似乎是最好的方式,但經過大量研究後,我仍然無法實現。整個PHP執行並沒有錯誤地結束,但是,不是顯示兩列中的所有10行,而是顯示兩列中值爲0的兩行,所有條目都爲值= 0。這是我使用的代碼:我做了一些調試和迴盪在foreach循環的$值
$sql2 = array();
foreach($_POST as key=>$value)
{
if(key != 'submit')
{
if($value != '')
{
$sql2[] = '("'.mysql_real_escape_string($value['db_num']).'", "'.$value['db_amnt'].'")';
}
}
}
mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',', $sql2));
,而且事實證明,這只是顯示三個學期; '數組','數組'和'提交'。進一步的檢查表明,我可以從提交表單獲取值的唯一方法是如果我通過$ _POST [db_num]和$ _POST [db_amnt]執行foreach循環而不是僅僅$ _POST。我不確定它爲什麼這樣做以及如何解決這個問題。這是我在PHP中的第一個代碼,我正在學習。我非常感謝任何幫助,我可以得到!
您對$ _ POST結構作出錯誤的假設。做print_r($ _ POST)來研究它,看看你是否可以解決如何修復腳本。 – Summoner 2012-07-30 11:55:26
陣列在POST數據中結束,比如提交複選框。另外,'key'應該是'$ key'。最後,將post數據轉儲到MySQL查詢中是個不錯的主意。如果有人更改DOM或以其他方式干擾該表單會怎麼樣?您允許它們潛在地破壞您的查詢,或者更糟糕。做適當的檢查和驗證。 – Utkanos 2012-07-30 11:56:43
提示:從提交中刪除「name」屬性。它沒有很多有用的信息,因此你不會在你的$ _POST中找到它。 – 2012-07-30 12:15:20