doutui2016 2010-11-17 12:22
浏览 52
已采纳

如果行不存在则插入

OK, firstly i know i havent checked user inputs and the code is a bit of a mess but its in testing at the moment, so its not a live system.

I have a table on one page, i'm using jQuery to go through each row and send the values as an array to a php page which goes through each row and updates the relevant row in the mysql db. Thtas great as long as you only want to edit what you've got. If the user adds another row to the table, it will still send all rows but i need the php to insert if it doesnt find the relevant row to update, that make sense?

This is my code for the php update as it is:

if (isset($_POST['data']) && is_array($_POST['data'])) {
              foreach ($_POST['data'] as $row => $data) {
                $sql = "UPDATE `orders` SET supp_short_code='".$data['supp_short_code']."', project_ref='".$data['project_ref']."', om_part_no='".$data['om_part_no']."', description='".$data['description']."', quantity=".$data['quantity_input'].", cost_of_items='".$data['cost_of_items']."', cost_total='".$data['cost_total_td']."' where order_id = ".$data['order_id']." and row_id = ".$data['index']."";
                $result = mysql_query($sql); 
              }
            }

The "index" is the row index from the table on the first page if that helps?

  • 写回答

3条回答 默认 最新

  • doujia4759 2010-11-17 12:30
    关注

    Just create an IF statement to check whether $data['index'] exists. If not then create an insert statement rather than an update.

    if (isset($_POST['data']) && is_array($_POST['data'])) {
              foreach ($_POST['data'] as $row => $data) {
                if($data['index']){
                  $sql = "UPDATE `orders` SET supp_short_code='".$data['supp_short_code']."', project_ref='".$data['project_ref']."', om_part_no='".$data['om_part_no']."', description='".$data['description']."', quantity=".$data['quantity_input'].", cost_of_items='".$data['cost_of_items']."', cost_total='".$data['cost_total_td']."' where order_id = ".$data['order_id']." and row_id = ".$data['index']."";
                } else {
                  $sql = /*Create INSERT statement*/;
                }
                  $result = mysql_query($sql); 
              }
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?