March 7, 2012

CodeIgniter outputting multiples of the same row

Question by Michael Grigsby

How can I keep the foreach statement from outputting multiple’s of the same row? I need it to just output all the rows that meet the Sql requirement one time. Any ideas?

$query  = $this->db->query("SELECT * FROM churchMembers WHERE cMuserId = '{$userid}'");
$row = $query->row();
$membersChurchId = $row->cMchurchId;
$query = $this->db->query("SELECT wp.entryData, u.firstname, u.userid
                           FROM wallPosts wp, users u
                           WHERE wp.wpChurchId = '{$membersChurchId}'");
foreach ($query->result() as $row) {
    echo $row->entryData.nl2br("n");
}

Answer by Starx

Update

After discussing the problem, it was the problem with the query.
The correct query in your case will be

$query = $this->db->query("SELECT wp.entryData, u.firstname, u.userid FROM users u INNER JOIN wallPosts wp on wp.postingUserid = u.userid WHERE wp.wpChurchId = '{$membersChurchId}'");

I think you are approaching this the wrong way.If you need to output all the rows, that meet your requirements, at one time, then you have to create a function, which reads the rows and build the output. But still you will be using the foreach

function buildAll($result) {
     $output = "";
     foreach($result as $row) { 
         $output .= $row->entryData."<br />"; //no need for nl2br("n")
     }
     return $output;
}

Now include this function in a helper or whatever you like as use it in your code like

$query = $this->db->query("SELECT wp.entryData, u.firstname, u.userid
                           FROM wallPosts wp, users u
                           WHERE wp.wpChurchId = '{$membersChurchId}'");

echo buildAll($query -> result()); //in one show

However the method I wrote above is only good, when you are using the function in more than one occasion

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!