dongyinglan8707 2012-06-15 22:21
浏览 49
已采纳

PHP / MYSQL插入数组Foreach循环

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. . . .

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.

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.

  • 写回答

2条回答 默认 最新

  • dqj96395 2012-06-15 22:40
    关注

    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');
    
     }
    

    Try that. Fixed your SQL query too. Correct syntax is

    INSERT INTO table_name (column1, column2, column3,...)
    VALUES (value1, value2, value3,...)
    

    You had put SELECT in place of VALUES

    Let me know if it works, and otherwise please tell what error it ives exactly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题