简体   繁体   中英

what is the correct way to process database?

The code below only deletes the data when I add the extra statement in the controller. why is that?

I've only been using codeigniter for a few months now and I keep getting stuck with weird bugs like this.

this is the models file:

My_model.php

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

and the code in controller:

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);
  }
}

it works fine until recently I tried to call this function via ajax like this:

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

You are using id in ajax param but using post_id as in your controller, which is undefined index.

You need to correct your index name as:

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

It's better to check what are you getting in controller by using print_r($_POST) this will you to understand, what kind of array are you getting from ajax data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM