CodeIgniter Forums
Noob w/ Select issues - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Noob w/ Select issues (/showthread.php?tid=23444)



Noob w/ Select issues - El Forum - 10-11-2009

[eluser]fildawg[/eluser]
Hi, Please excuse the question from a noob. I'm trying to select a row from a table and then use the elements for futher logic. Here's the code:

$query = $this->db->select('code, expires_dt, amount');
$query = $this->db->from('promotions');
$query = $this->db->where('code', $coupon_code);
$query = $this->db->get();

echo 'Num_rows: ' . $query->num_rows();
echo 'Amount: '. $query->amount;

How can I access the data selected?

TIA!


Noob w/ Select issues - El Forum - 10-11-2009

[eluser]InsiteFX[/eluser]
Code:
if ($query->num_rows() > 0)
{
   $row = $query->row();

   echo $row->title;
   echo $row->name;
   echo $row->body;
}

Enjoy
InsiteFX


Noob w/ Select issues - El Forum - 10-11-2009

[eluser]fildawg[/eluser]
much obliged!


Noob w/ Select issues - El Forum - 10-11-2009

[eluser]ggoforth[/eluser]
You also don't need to assign the $query variable to each part of the active record. You technially only have to assign the variable to the ->get() to hold the result. You could rewrite it as:

Code:
$this->db->select(‘code, expires_dt, amount’);
$this->db->from(‘promotions’);
$this->db->where(‘code’, $coupon_code);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
   $row = $query->row();

   echo $row->title;
   echo $row->name;
   echo $row->body;
}



Noob w/ Select issues - El Forum - 10-12-2009

[eluser]BrianDHall[/eluser]
Just for fun, in PHP 5 if you wanna you can use method chaining:

Code:
$query = $this->db->select(‘code, expires_dt, amount’)->from(‘promotions’)->where(‘code’, $coupon_code)->get();

You don't have to, but I enjoy not having to repeatedly type $this->db all the time Smile


Noob w/ Select issues - El Forum - 10-12-2009

[eluser]fildawg[/eluser]
Wow! Thanks to all! I really appreciate the info.

Brian - Thanks - I do think the code is a little odd repeating the $this->db all the time. I'll try chaining.