• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple recordset question

#1
[eluser]Chad Crowell[/eluser]
I am using active record to pull data from the db in the model and push it to the view through the controller, no problem.

If I am pushing a recordset with multiple rows, I have no problems getting data to display with something like this:

Code:
<?php if (is_array($entries)) : foreach ($entries as $entry) : ?>
<h2><a href="&lt;?=site_url('speak/post/'.$entry->id)?&gt;">&lt;?=$entry->entry_title;?&gt;</a></h2>
<p>&lt;?=$entry->entry_text;?&gt;</p>
&lt;? endforeach; else: ?&gt;
&lt;?=$entry;?&gt;
&lt;? endif; ?&gt;

The above code will loop through all records and display them.

However, I can't seem to place the data from the recordset on the page when there is only a single record returned without doing a for each loop, which places the record data into a variable ($entry in the above example). So imagine a blog, and I want to show the info from the db when looking at a post's own page... so I will want the title, body, date, author. But there will only be one row in the recordset returned since this is the specific page for a specific post.

How do I move that one row of data into a variable without using the same code as above, then display the data? I couldn't really find anything concrete in the user guide. I found a few examples but couldn't make them work.

#2
[eluser]Michael Wales[/eluser]
Hmm... so you are wanting to not reuse code? I don't quite understand that - if it works, reuse it. But, for kicks - here you go - how to pull one record down in the model and display it in the view:

models/posts.php
Code:
function get_post($id) {
  $query = $this->db->getwhere('posts', array('id'=>$id), 1, 0));
  $post = $query->row();
  return array('title'=>$post->title, 'body'=>$post->body, 'date'=>$post->date, 'author'=>$post->author);
}

controllers/blog.php
Code:
function view($id) {
  $this->load->model('posts');
  list($data['title'], $data['body'], $data['date'], $data['author']) = $this->posts->get_post($id);
  $this->load->view('single', $data);
}

views/single.php
Code:
&lt;html&gt;
  &lt;body&gt;
    <h2>&lt;?= $title; ?&gt;</h2>
    <h3>Posted by &lt;?= $author; ?&gt; on &lt;?= $date; ?&gt;</h3>
    <p>&lt;?= body; ?&gt;</p>
  &lt;/body&gt;
&lt;/html&gt;

#3
[eluser]Chad Crowell[/eluser]
I didn't say I don't want to re-use code. I am not sure where you got that from. I'm just asking for pulling one record and displaying it in a manner that doesn't force me to use a foreach loop. Thanks for your help.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


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