John Hoffman
John Hoffman

Reputation: 18627

How do I concisely return the first result in a Code Igniter query?

I tried to return an object representing a journal retrieved based on its ID in a model.

public function getJournal($id) {
    $query = $this->db->query("SELECT * FROM journals WHERE id='$id'");
    return ($query->num_rows() == 1) ? ($query->result())[0] : NULL;
}

However, PHP issues an error declaring an unexpected open right bracket ([).

I ended up actually looping through the array of 1 object entity to return it, which is silly but works.

public function getJournal($id) {
    $query = $this->db->query("SELECT * FROM journals WHERE id='$id'");
    if ($query->num_rows() == 1) {
        foreach ($query->result() as $journal)
            return $journal;
    }
    else
        return NULL;
}

What is a more concise way to return this object?

Upvotes: 4

Views: 1609

Answers (4)

Chuwiey
Chuwiey

Reputation: 56

First off, you should limit your query to 1:

SELECT * FROM journals WHERE id='$id' LIMIT 1

Secondly, the reason it was stating that there was an unexpected open right bracket. This is because the result method in codeigniter returns an object and not an array. You could use ->result_array(); if you want that... but if you decided to limit to 1, you could just as well return the object...

Good luck

Upvotes: 1

landons
landons

Reputation: 9547

public function getJournal($id)
{
    return $this->db->where('id', $id)->get('journals')->row() ?: NULL; // (requires PHP 5.3)
}

Upvotes: 3

Rob
Rob

Reputation: 12872

public function getJournal($id) {
    $id = (int) $id;
    $query = $this->db->query("SELECT * FROM journals WHERE id = $id limit 1");
    if ($query->num_rows() == 1) {
        return $query->row();
    }
    return NULL;
}

Upvotes: 1

rjz
rjz

Reputation: 16510

Instead of grabbing the result(), just use the row() method:

$first_result = $query->row();

Upvotes: 8

Related Questions