处理数据库的正确方法是什么?

时间:2016-11-16 08:46:53

标签: php mysql ajax codeigniter

以下代码仅在控制器中添加extra语句时删除数据。那是为什么?

我现在只使用了codeigniter几个月而且我一直遇到像这样的奇怪错误。

这是模型文件:

My_model.php

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

和控制器中的代码:

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

1 个答案:

答案 0 :(得分:1)

您在ajax param中使用id但在控制器中使用post_id,这是未定义的索引。

您需要将索引名称更正为:

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

最好通过print_r($_POST)来检查你在控制器中得到了什么,这将使你明白,从ajax数据中得到什么样的数组。