[英]looping through multiple arrays and inserting into SQL
我有一個表單,一旦提交,它的一些結果就會存儲在數組中,例如:
(表單中有多行具有相同的輸入名稱)
<select name="product[]">
提交后進入$_GET['product']
如果我做:
// Product ID's
foreach($_GET['product'] as $name => $prodvalue) {
print "$name : $prodvalue<br>";
}
返回以下內容:
0:9
1:10
2:11
3:12
除了產品ID之外,我還有2個其他表單輸入的結構相同,所以我的問題是如何遍歷$ _GET的每一個( $_GET['product']
, $_GET['linequantity']
和$_GET['lineprice']
)將它們中的每一個添加到多個SQL表行中? 另外,還需要輸入其他記錄 ,但是這些記錄將是恆定的,因此,例如,如果要添加3行,則其他記錄對於這3行中的每行都是相同的。
請幫助我,我瘋了!
B.
編輯:
該表稱為:order_lines
值=>字段
$ _GET ['product'] => product_id
$ _GET ['linequantity'] =>單價
$ _GET ['lineprice'] =>數量
$ unh =>取消
還有更多,但是,我可以從那里解決。
如果所有表單字段數組的鍵都相等,則可以使用一個的名稱來引用另一個:
$values = array();
foreach ($_GET['product'] as $name => $value) {
$values[] = array($value, $_GET['linequantity'][$name], $_GET['lineprice'][$name]);
}
這將創建一個數組,其中每個元素都是具有相關字段的數組:
假設每個集合中的項目數相同,我將采用以下方式:
$staticValue1 = $_GET['value1'];
$staticValue2 = $_GET['value2'];
foreach($_GET['product'] as $name => $prodvalue) {
$name = my_escape($name);
$prodvalue = my_escape($prodvalue);
$linequantity = my_escape($_GET['linequantity'][$name]);
$lineprice = my_escape($_GET['lineprice'][$name]);
if (checkFormat($linequantity, $lineprince, $prodvalue, $name, $staticValue1, $staticValue2) {
$query = "INSERT INTO <table> (qty, unit_price, product, name, static_value_1, static_value_2) VALUES ".
"(".$linequantity.", '".$lineprice."', '".$prodvalue."', '".$name."', '".$staticValue1."', '".$staticValue2."')";
$result = mysql_query($query);
}
}
function my_escape($input) {
//filter chars that will cause problems in the database
// then return the filtered values; depends on db
// usually this means encoding quotes, at the very least
return str_replace("'","/'",$input);
}
function checkFormat($linequantity, $lineprince, $prodvalue, $name, $staticValue1, $staticValue2) {
//use a series of comparisons to return true or false
// based on whether or not ALL inputs match the expected range of values
if (!(is_numeric($linequantity)) return false;
... //<-- more comparisons
return true; // <-- reaching this means it did not fail on any checks
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.