2

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.

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);
TylerH
  • 20,799
  • 66
  • 75
  • 101
Nira
  • 197
  • 1
  • 1
  • 12
  • Looks a lot like an auto incremented primary key to me... – Kzryzstof Aug 03 '18 at 10:11
  • I edited my question: 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. – Nira Aug 03 '18 at 10:13

2 Answers2

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);
manish
  • 423
  • 3
  • 9
1

$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'),
);
vasilenicusor
  • 2,023
  • 1
  • 21
  • 37