douwei7976 2014-08-06 19:20
浏览 59

无法循环访问mysql_insert_id()以获取多个条目

I'm retrieving last id of tbl_orderdetail(table 1) in order to add addon items entries into tbl_orderdetail_addon(table 2). Basically it should insert into (table 2) as per the number of ids received from (table 1). I'm using mysql_insert_id() for that.

i'm getting that right but the ids are not looping through. It inserts the same id of (table 1) for all entries in (table 2). Say that I have two entries in (table 1),obviously it should return 2 id's.And each id has 2 add on items .So in (table 2) there should be four entries with 2 different id's of (table 1). IN my case Im getting 4 entries of same id of (table 1).
Here's my coding:

$o_id_detail=mysql_insert_id();//(table 1) id
foreach($addon_price as $a_p=>$p)// 
     { 
         echo $a_p;
           foreach($p as $m)
              {

                 $addon_id= $m['id'];
                 echo $m['addon_name'];
                 echo $m['deposit'];
                 echo $m['ppd'];
                 echo $m['pp_eight'];
                 echo $m['pp_six'];


$addon_total=$m['deposit']+$m['ppd']+$m['pp_eight']+$m['pp_six'];
                 echo $addon_total;



                  $addon_detail="INSERT INTO tbl_orderdetail_addon (OrderID,addOns_id,addOns_price) VALUES ('$o_id_detail','$addon_id','$addon_total')";
                               if(!empty($addon_id))
                                {
                                  mysql_query($addon_detail)or die(mysql_error());


                                 }
                    }     

        }

Any help would be greatly appreciated.Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doushouj966020 2014-08-06 21:15
    关注

    Basically it should insert into (table 2) as per the number of ids received from (table 1)

    mysql_insert_id() only returns a single int value. As described in the manual:

    Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

    You need to insert the first row to table1 then the corresponding rows in table2; insert the second row to table1 then the corresponding rows in table2; etc.

    Pseudo-code to explain the previous paragraph:

    foreach order_detail {
        insert order_detail;
        get last_insert_id;
        foreach order_detail_addon {
            insert order_detail_addon with last_insert_id;
        }
    }
    

    Edited to add:

    Your code is vulnerable to SQL Injection. Read this and also see what the PHP manual says about it.

    And you should stop using the mysql_* functions.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。