Welcome Guest, Not a member yet? Register   Sign In
How NOT to use foreach when expecting only 1 record?
#1

[eluser]Slowcheetah[/eluser]
I'm wondering if and how it's possible to NOT use foreach when expecting only one record as a result.

My current model code:
Code:
function get_user_id($username, $useremail)
    {
        $this->db->where('username', $username);
        $this->db->where('email', $useremail);
        $query = $this->db->get('accounts', 1);
        if ($query->num_rows() == 1)
        {
            foreach ($query->result() as $row)
            {
                return $row->id;
            }
        }
    }
#2

[eluser]Michael Wales[/eluser]
Code:
if ($query->num_rows() == 1) {
  $row = $query->row();
  return $row->id;
}
#3

[eluser]Slowcheetah[/eluser]
nice Big Grin
#4

[eluser]Dam1an[/eluser]
When I read the title, I was expecting this to be one of those posts where you intentioanlly do something in the most complicated way when its a one liner

@slowcheetah: And I had the same problem when I first started using CI as all I saw in all the examples at the time was ->result() (Back in those days, the thought of having to refer to documentation seemed unimaginable)
#5

[eluser]jdfwarrior[/eluser]
[quote author="Dam1an" date="1242068413"](Back in those days, the thought of having to refer to documentation seemed unimaginable)[/quote]

Wait.. what?! So that's how you guys know all this stuff. You've been cheating! You read the User Guide!
#6

[eluser]Dam1an[/eluser]
[quote author="jdfwarrior" date="1242069237"]Wait.. what?! So that's how you guys know all this stuff. You've been cheating! You read the User Guide![/quote]

I wouldn't go as far as saying cheating... just... emm... fine, I cheated Sad
I wonder how many people here have actually read the ENTIRE user guide... (I have... had a very slow day at work)
#7

[eluser]jdfwarrior[/eluser]
[quote author="Dam1an" date="1242069420"][quote author="jdfwarrior" date="1242069237"]Wait.. what?! So that's how you guys know all this stuff. You've been cheating! You read the User Guide![/quote]

I wouldn't go as far as saying cheating... just... emm... fine, I cheated Sad
I wonder how many people here have actually read the ENTIRE user guide... (I have... had a very slow day at work)[/quote]

Ok so I guess I have to do it too now. Gotta follow the crowd.

I've read a good bit of it. I've had a lot of slow days at work and procrastinate a lot as well. Smile
#8

[eluser]xwero[/eluser]
[quote author="Michael Wales" date="1242067314"]
Code:
if ($query->num_rows() == 1) {
  $row = $query->row();
  return $row->id;
}
[/quote]
I would remove the row count check if the method has to return one row/value
Code:
$row = $query->row();

return (isset($row->id))? $row->id : false ;
#9

[eluser]Michael Wales[/eluser]
Nice xwero! I don't use the ternary operators as much as I should...




Theme © iAndrew 2016 - Forum software by © MyBB