【问题标题】:what is the correct way to process database?处理数据库的正确方法是什么?
【发布时间】:2016-11-16 08:46:52
【问题描述】:

下面的代码仅在我在控制器中添加额外语句时删除数据。这是为什么呢?

我现在只使用了几个月的 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.');
  }
});

【问题讨论】:

  • 你需要使用$id$_POST
  • @devpro 对不起,我是凭记忆写这个问题的,在我检查代码错误之后..我编辑了代码。请看一下
  • 是的,你在这里使用了错误的索引名称$id = $this->input->post('post_id', TRUE);这应该是$id = $this->input->post('id', TRUE);
  • 在控制器中检查print_r($_POST)并分享结果同时检查浏览器控制台
  • 当我用print_r($this->input->post()) 替换额外的语句时,它给出了array([post_id] => 12),这是正确的。不管怎样,我又测试了几次代码后,发现问题出在代码的另一部分。无论如何谢谢:)

标签: php mysql ajax codeigniter


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 1970-01-01
    • 2012-11-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多