sehummel
sehummel

Reputation: 5568

Retrieve a single row from Codeigniter

If I need to retrieve a single row of data from the database, why can't I do this when I want to insert that id into another table:

'user_id' => $query->row()->id

Is there any way to do this without a foreach loop if all I want is a single piece of data?

The full code is:

$this->db->where('username', $this->input->post('username'));
        $query = $this->db->get('members');

        $data = array(
            'first' => $this->input->post('first'),
            'last' => $this->input->post('last'),
            'email' => $this->input->post('email'),
            'phone' => $this->input->post('phone'),
            'address' => $this->input->post('address'),
            'city' => $this->input->post('city'),
            'state' => $this->input->post('state'),
            'zip' => $this->input->post('zip'),
            'comments' => $this->input->post('comments'),
            'username' => $this->input->post('username'),
            'user_id' => $query->row()->id
        );

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

Upvotes: 0

Views: 13063

Answers (2)

gen_Eric
gen_Eric

Reputation: 227310

$query->row()->id is correct, yes. Given that the field is called 'id' in your table, and the row exists that you want. You can check $query->num_rows() to see how many rows were returned.

Upvotes: 2

Ross
Ross

Reputation: 17987

$the_data= $query->row();

$user_id= $the_data->id;

don't think you can do method chaining like in your example.

Upvotes: 0

Related Questions