Jack
Jack

Reputation: 153

Multiple ActiveRecord Queries in CodeIgniter

I want to do the following:

//set up insert....
$this->db->insert('property');
$id = $this->db->insert_id();
//some stuff
//set up get
$this->db->where('id', $id);
$id = $this->db->get();

This does not work. It would appear the insert is not being executed before the get - the get is returning zero rows. The insert does (eventually) work. Any suggestions?

Upvotes: 1

Views: 1645

Answers (2)

Colin Brock
Colin Brock

Reputation: 21565

You're missing an argument - insert() takes two:

  1. A table name
  2. An array or object containing columns and values

From the documentation:

$data = array(
   'title' => 'My title' ,
   'name' => 'My Name' ,
   'date' => 'My date'
);

$this->db->insert('mytable', $data); 

// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

So, you need to supply insert() with the necessary data by including an array or object as the second argument.

Edit:

Alternatively, you can use the $this->db->set() method for setting values, as explained in Rocket's more comprehensive answer, which also points out you need to specify a table when selecting data.

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227220

You need to give insert some data to insert.

With either the set method:

$this->db->set('name', 'Eric');
$this->db->insert('property');

or by passing an array as the 2nd parameter:

$this->db->insert('property', array(
   'name' => 'Eric'
));

As, for your select, you need to tell it what table to select from.

Use either the from method:

$this->db->from('property');
$this->db->where('id', $id);
$id = $this->db->get();

or pass get a table as a parameter:

$this->db->where('id', $id);
$id = $this->db->get('property');

Also, note that get() returns a query object. You need to use ->row (or ->result) to get the data.

$this->db->from('property');
$this->db->where('id', $id);
$query = $this->db->get();
$id = $query->row()->id;

Upvotes: 2

Related Questions