簡體   English   中英

處理數據庫的正確方法是什么?

[英]what is the correct way to process database?

當我在控制器中添加額外的語句時,下面的代碼僅刪除數據。 這是為什么?

我現在只用了幾個月的codeigniter,而我一直被這種奇怪的錯誤困擾。

這是模型文件:

My_model.php

function delete_data($where=array())
{
  return $this->db->delete('table1', $where);
}

和控制器中的代碼:

task.php

function do_delete_data()
{
  $this->load->model('My_model');
  $result = array('status' => '', 'message' => '');
  try
  {
    $this->db->trans_begin();
    $id = $this->input->post('post_id', TRUE);
    if ( ! $this->My_model->delete_data(array('id' => $id)))
    {
      throw new Exception('Database process failed.');
    }
    $result['message'] = $this->db->last_query(); // extra statement
    $this->db->trans_commit();
    $result['status'] = 1;
  }
  catch(Exception $e)
  {
    $this->db->trans_rollback();
    $result['message'] = $e->getMessage();
  }

  if ($this->input->is_ajax_request())
  {
    echo json_encode($result);
  }
}

直到最近我嘗試通過ajax調用此函數,它的工作正常,如下所示:

display.php

$.ajax({
  url: '/tasks/do_delete_data',
  type: 'post',
  data: {
    'post_id' : $('#post_id').val(), // e.g. 12
  },
  dataType: 'json',
  success: function(response) {
    alert('File deleted successfully.');
    console.log(response);
  },
  error: function(e) {
    alert('an error occurred.');
  }
});

您在ajax參數中使用id ,但在控制器中使用post_id ,這是未定義的索引。

您需要將索引名稱更正為:

$id = $this->input->post('id', TRUE); // use id

最好使用將要理解的print_r($_POST)來檢查您要在控制器中獲得什么,從ajax數據中獲得什么樣的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM