Codeigniter, mysql, select_max and add 1 before in

2019-05-25 08:55发布

问题:

When I insert a new record into a database table, I need to take an existing previous value of a column called el_order, add +1, and use that new el_order+1 to insert the new record with that value in the column.

I can't use autoincrement because I need to do some things with that column (reorder, move, etc) and have to use it as an integer.

My english isn't good, so I will explain like this:

Table

   ID      name    el_order
   1         1         1
   21       bla        2
   2        2          3
--NEW--   --NEW--     3+1 (NEW)

I add a new record, and need to insert it with 3+1 in it's el_order column...

I have tried this, but no luck:

$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio');

$eldi_key = url_title($this->input->post('id'), 'underscore', TRUE);

$el_order = $res+1;

$datos = array(
    'ID' => $id,
    'el_order' => $el_order,
     'name' => $this->input->post('name'),
 );

 $this->db->insert('elem_diccio', $datos);

Thanks.

回答1:

Just like this

 $this->db->select_max('el_order');
 $res = $this->db->get('elem_diccio')->row()->el_order;

 $eldi_key = url_title($this->input->post('id'), 'underscore', TRUE);

 $el_order = $res+1;

$datos = array(
  'ID' => $id,
  'el_order' => $el_order,
  'name' => $this->input->post('name'),
);

$this->db->insert('elem_diccio', $datos);


回答2:

  1. Update query increment field plus 1 codeigniter

  2. Update the value of a field in database by 1 using codeigniter

Please check above two links for the answer that you seek. Thanks



回答3:

$res is a CI_DB_mysqli_result Object. To get the column, you need

$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio')->row();
$el_order = $res->el_order+1;

$datos = array(
    'ID' => $id,
    'el_order' => $el_order,
    'name' => $this->input->post('name'),
);