• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
MySQL Loop

#1
[eluser]georgerobbo[/eluser]
Okayy, I am probably trying to accomplish too much for a beginner. I have a sidebar where I have a multiple sub divs.

Code:
div id="sidebar">
            
        <div class="sideitem">
            <div class="sidetitle">
                <h3>&lt;?php echo $sidetitle['1']; ?&gt;</h3>
            </div>
                <p>&lt;?php echo $sidecont['1']; ?&gt;</p>
        </div>
        
        <div class="sideitem">
            <div class="sidetitle">
                <h3>&lt;?php echo $sidetitle['2']; ?&gt;</h3>
            </div>
                <p>&lt;?php echo $sidecont['2']; ?&gt;</p>
        </div>

What I want to accomplish is for code-igniter to pull the information from an MySQL database, insert the values into an associative array like above and then for the <div class="sideitem"> to work on a loop. I'm struggling getting the database results into an associative array and then into the tags.

#2
[eluser]jcavard[/eluser]
Well, if you want an associative array, I guess you can just use
Code:
$this->db->select('field1, field2');
$this->db->from('table1');
$handle = $this->db->get();

foreach($handle->result_array() as $row)
{
  echo $row['field1'] . '<br />';
  echo $row['field2'] . '<br />';
}

#3
[eluser]bigtony[/eluser]
Personally I use Active Record for the database stuff, so in your model you'll have something like this...
Code:
function load_all() {
    $this->db->from('tablename');
    return $this->db->get();
}
Then your controller can get the data from the model and pass it to the view...
Code:
$this->load->model('tablename_model')
$tablename_query = $this->tablename_model->load_all();
$view_data['tablename_query'] = $tablename_query;
$this->load->view('pagename_view', $view_data);
Then in your view you can loop through the resultset like this...
Code:
<div id="sidebar">
    &lt;?php foreach ($tablename_query->result() as $row_of_data): ?&gt;
        <div class="sideitem">
            <h3>&lt;?php echo $row_of_data->column_name; ?&gt;</h3>
        </div>
    &lt;?php endforeach; ?&gt;
</div>
or using an associative array...
Code:
<div id="sidebar">
    &lt;?php foreach ($tablename_query->result_array() as $row_of_data): ?&gt;
        <div class="sideitem">
            <h3>&lt;?php echo $row_of_data['column_name']; ?&gt;</h3>
        </div>
    &lt;?php endforeach; ?&gt;
</div>


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.