Welcome Guest, Not a member yet? Register   Sign In
Changing db results in model before passing
#2

[eluser]bretticus[/eluser]
Calling $sql->result_array() only pulls one record at a time (hence, the reason you are using a foreach loop to check titles, etc.) Your example will only return the first record. Another thing to note, When you iterate over $sql, $row is not passed by reference, so working on $row will never alter the result row. If you had some large array of arrays, you could pass $row by reference (with an ampersand), but that's not an option in CodeIgniter, so, this has to be done programmatically (well, it is. You just write the code instead of using CI code.)

Here's what I do (not always but sometimes I guess,) I set an empty array:

Code:
$results = array();

I then iterate over the query using result_array():

Code:
$sql = "query here";
        $sql = $this->db->query($sql);
        foreach($sql->result_array() as $row)
        {
             $results[] = $row;
        }

After that loop, you will have a $results array with all your data. Now you can iterate over that to modify data.

Code:
foreach($results as &$row)
        {
             if(strlen($row['title'])==50)
             {
             echo "is 50!";
             $row['title']=$row['title']."...";
             }
        }

return $results;

Don't forget the ampersand because that's how you pass by reference and that's how your $results array can be modified inside the foreach loop.

You might want to change your code a little though. It's probably very unlikely your titles will be exactly 50 characters long to make this code worhtwhile. May I recommend:


Code:
foreach($results as &$row)
        {
             if(strlen($row['title'])>=50)
             {
             echo "is 50!";
             $row['title']=substr($row['title'],0,50)."...";
             }
        }

return $results;

Just using substr() to force 50 chars for the result.


Messages In This Thread
Changing db results in model before passing - by El Forum - 09-21-2010, 02:45 PM
Changing db results in model before passing - by El Forum - 09-21-2010, 04:26 PM
Changing db results in model before passing - by El Forum - 09-21-2010, 05:40 PM
Changing db results in model before passing - by El Forum - 09-21-2010, 08:30 PM
Changing db results in model before passing - by El Forum - 09-22-2010, 09:53 AM
Changing db results in model before passing - by El Forum - 09-22-2010, 10:01 AM
Changing db results in model before passing - by El Forum - 09-22-2010, 10:21 AM
Changing db results in model before passing - by El Forum - 09-22-2010, 10:26 AM
Changing db results in model before passing - by El Forum - 09-22-2010, 10:37 AM
Changing db results in model before passing - by El Forum - 09-22-2010, 11:01 AM
Changing db results in model before passing - by El Forum - 09-22-2010, 11:38 AM
Changing db results in model before passing - by El Forum - 09-22-2010, 12:05 PM



Theme © iAndrew 2016 - Forum software by © MyBB