dongou5100 2018-07-11 14:07
浏览 63
已采纳

使用php MVC / ajax / json删除多条记录时的foreach问题

I am listing a table which shows records from the database and each row has a checkbox with an ID value associated with it.

<label class="m-checkbox">
 <input type="checkbox" name="order_id[]" value="<?php echo sanitize($failed->order_id); ?>">
 <span></span>
</label>

Once the user has selected the checkboxes of the records they want to delete, the submit button is pressed and that triggers an ajax request.

$( '.delete-failed' ).on('click', function(e) {
    e.preventDefault();
    var form = $( '#delete-failed' ).serialize();
    $.ajax({
        url: url + '/TransactionsAjax/deleteFailedTransactions',
        type: 'POST',
        data: form,
        dataType: 'json',
        beforeSend: function() {
            $( 'delete-failed' ).prop('disabled', true);
        }
    })
    .done(function (data) {
        if(!data.success) {
            $( '.alert-danger' ).append(data.message).fadeIn();

        } else {


            $( '.alert-success' ).append(data.message).fadeIn();
        }
    })
            .fail(function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
            console.warn(jqXHR.responseText);
        });
});

That then goes to the controller:

if($_SERVER['REQUEST_METHOD'] === 'POST') {

    $response = array();
    $message = '';


    $orderId = $_POST['order_id'];

    $data = [

        'order_id' => $orderId
    ];

    if($this->TransactionsModel->deleteFailedTransactions($data)) {
        $response['success'] = true;
        $response['message'] = 'Failed transactions deleted';

    } else {

        $response['success'] = false;
        $response['message'] = 'Something went wrong. Please try again later.';
    }

    echo json_encode($response);    
}

Which is supposed to send the data to the model:

public function deleteFailedTransactions($data)
    {
        $this->db->beginTransaction();

        try {

            $this->db->query("DELETE FROM `order_summary` WHERE `order_id` = :order_id");
            $this->db->bind(":order_id", $order_id);

            foreach($data as $item) {
                $order_id = $item['order_id'];
                $this->db->execute();
            }


            $this->db->query("DELETE FROM `order_detail` WHERE `order_id` = :order_id");
            $this->db->bind(":order_id", $order_id);

            foreach($data as $item) {
                $order_id = $item['order_id'];
                $this->db->execute();
            }

            $this->db->commit();
            return true;
        }

        catch(Exception $e) {
            $this->db->rollBack();
            echo $e;
            return false;
        }
    }

The error I am getting in console is:

undefined index: order_id

It is referring to this line in the model:

$order_id = $item['order_id'];

I am not sure at which point the problem is, is it in the data being sent via ajax, should the foreach loop be in the controller instead.. I am not sure.

  • 写回答

1条回答 默认 最新

  • douma5954 2018-07-11 14:58
    关注

    The problem stems from the mishandling of data and variable names; that is, consider how you are wrapping and passing data. Are you intending to pass one order id from the checkboxes at a time in the ajax, or multiple? It's unclear, so I've modified the code to handle one order id. If it's multiple, you need to loop in the controller and properly create an array of order ids from the post, and then properly foreach loop over each order id in the model and bind and execute the query for each. Make sure you're looping over the object actually holding the list of ids.

    For one issue, in your model $order_id doesn't exist, you only passed in the $data variable, you might be looking for $data['order_id'], or simply passing in $order_id without encompassing it in the $data array.

    Similarly, this $data variable seems to be just an array that contains one order_id. It makes no sense to foreach loop on $data when it is hardcoded to contain one key,value pair.

    I would try this:

    if($_SERVER['REQUEST_METHOD'] === 'POST') {
    
      $response = array();
      $message = '';
    
      $orderId = $_POST['order_id'];
    
      if($this->TransactionsModel->deleteFailedTransactions($orderId)) {
        $response['success'] = true;
        $response['message'] = 'Failed transactions deleted';
    
      } else {
    
        $response['success'] = false;
        $response['message'] = 'Something went wrong. Please try again later.';
      }
    
      echo json_encode($response);    
    }
    

    And then the model:

    public function deleteFailedTransactions($order_id)
    {
        $this->db->beginTransaction();
    
        try {
    
            $this->db->query("DELETE FROM `order_summary` WHERE `order_id` = :order_id");
            $this->db->bind(":order_id", $order_id);
    
            $this->db->execute();
    
            $this->db->query("DELETE FROM `order_detail` WHERE `order_id` = :order_id");
            $this->db->bind(":order_id", $order_id);
    
            $this->db->execute();
    
            $this->db->commit();
            return true;
        }
    
        catch(Exception $e) {
            $this->db->rollBack();
            echo $e;
            return false;
        }
    }
    

    Seeing your html have order_id[] indicates you may be trying to send multiple. Depending on how data is passing, you may need to explode/implode the list differently than I am. Consider this:

    if($_SERVER['REQUEST_METHOD'] === 'POST') {
    
      $response = array();
      $message = '';
    
      $orderIds = $_POST['order_id']; //explode maybe
    
      if($this->TransactionsModel->deleteFailedTransactions($orderIds)) {
        $response['success'] = true;
        $response['message'] = 'Failed transactions deleted';
    
      } else {
    
        $response['success'] = false;
        $response['message'] = 'Something went wrong. Please try again later.';
      }
    
      echo json_encode($response);    
    }
    

    And then the model:

    public function deleteFailedTransactions($order_id)
    {
        $this->db->beginTransaction();
    
        try {
            foreach($order_id as $id) {
              $this->db->query("DELETE FROM `order_summary` WHERE `order_id` = :order_id");
              $this->db->bind(":order_id", $id);
    
              $this->db->execute();
            }
    
            foreach($order_id as $id) {
              $this->db->query("DELETE FROM `order_detail` WHERE `order_id` = :order_id");
              $this->db->bind(":order_id", $id);
    
              $this->db->execute();
            }
    
            $this->db->commit();
            return true;
        }
    
        catch(Exception $e) {
            $this->db->rollBack();
            echo $e;
            return false;
        }
    }
    

    And you might consider optimizing the foreach queries into one each, like this:

      $this->db->query("DELETE FROM `order_summary` WHERE `order_id` IN (:order_id)");
      $this->db->bind(":order_id", implode(",",$order_id); //whatever gives you comma separated string
      $this->db->execute();
    

    Note that I'm not running this code, so consider it guidance/PHP oriented pseudocode for you to figure it out yourself. Feel free to ask clarifying questions via DM.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。