PHP / MYSQL插入数组Foreach循环 [英] PHP / MYSQL Insert Array Foreach Loop
问题描述
这个让我非常不高兴,所以在此先感谢您的帮助。关于此主题似乎有很多演练,但看来我可能对这只猫的皮肤有些不同。 。 。 。
This one has me pretty rattled so I thank you in advance for your assistance. There seem to be a number of walkthroughs on this topic but it seems I may be skinning this cat a bit different. . . .
我有一个使用javascript的采购订单表格,用于向表格中动态添加行并捕获多个订单项的数据。然后,我要收集数组中每一列的数据。例如,我有 Cust_PN,数量,价格作为每个的列和数组。 。 。订单项1-3的Cust_PN [0] Cust_PN [1]和Cust_PN [2]。然后,我会有Qty [0],Qty [1]和Qty [2]等。
I have a purchase order form that I'm using javascript to dynamically add rows to a table and capture data for multiple line items. I'm then collecting data for each column in an array. For example I have "Cust_PN", "Qty", "Price" as columns and arrays for each. . . Cust_PN[0] Cust_PN[1] and Cust_PN[2] for line items 1-3 respectively. I then have Qty[0], Qty[1], and Qty[2] and so on.
我可以使它正确地回显而不会出现问题。但是,当我发布时,我只是按照上面的示例发布了最后一个条目* [3]中的数组数据。
I can get this to echo properly without issue. However, when I go to post I am only posting the array data from the last entry *[3] per my example above.
我目前有以下代码/查询。 。 。
I currently have the following code/query. . . again any help would be much appreciated.
$query1 = "INSERT INTO SO_Items (Timestamp,SO_Num,SO_Rev,SO_Line_Item,Cust_PN,Cust_PN_Rev,My_PN,My_PN_Rev,Description,
Qty,Sale_Price,UOM,Program,Required_Date)
SELECT NOW(),'$SO_Num','$SO_Rev','$SO_Line_Item[$a]','$Cust_PN[$a]','$Cust_PN_Rev[$a]','$My_PN[$a]','$My_PN_Rev[$a]','$Description[$a]','$Qty[$a]','$Sale_Price[$a]','$UOM[$a]','$Program[$a]','$Required_Date[$a]'" or die ('Error posting data');
foreach($Cust_PN as $a => $b) {
mysql_query($query1);
}
我很确定上面有很多问题。 。 。
I'm quite certain there are a number of issues in the above. . . thank you in advance.
推荐答案
您的主要问题是,声明 $ query
在循环之外。
使其成为常数,并且也取值 $ a
和 $ b
时间,未定义,因此会导致SQL语法无效。
Your main issue is, declaring $query
outside the loop.
It makes it a constant, and that too, takes values $a
and $b
which are that time, undefined, so results in invalid syntax for SQL.
foreach($Cust_PN as $a => $b) {
$query1 = "INSERT INTO SO_Items (Timestamp, SO_Num, SO_Rev, SO_Line_Item, Cust_PN, Cust_PN_Rev, My_PN, My_PN_Rev, Description, Qty, Sale_Price, UOM, Program, Required_Date) VALUES (NOW(), '$SO_Num', '$SO_Rev', '$SO_Line_Item[$a]', '$Cust_PN[$a]', '$Cust_PN_Rev[$a]', '$My_PN[$a]', '$My_PN_Rev[$a]', '$Description[$a]', '$Qty[$a]', '$Sale_Price[$a]', '$UOM[$a]', '$Program[$a]', '$Required_Date[$a]');";
$q = mysql_query($query1) or die ('Error posting data');
}
尝试一下。
也修复了您的SQL查询。正确的语法是
Try that. Fixed your SQL query too. Correct syntax is
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
您已放置 SELECT
代替 VALUES
让我知道它是否有效,否则请告诉它它出现了什么错误
Let me know if it works, and otherwise please tell what error it ives exactly.
这篇关于PHP / MYSQL插入数组Foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!