繁体   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