Separate out queries from the output page?

Hi,
so for years i have been writing my mysqli queries within the same page as the output of the query. eg

Query at top of the page
Echo results of the query somewhere in the page below
or
Query within the body of the page
Echo results directly below.

I have seen others doing this differently by having an included page of functions that contain the queries and the results outputted on a separate page. What are the advantages of doing this? Should i be doing this?

I am not sure what to google to read about it. Most tutorials just have the query next to the output. If that is perfectly fine then i’ll continue to do that, just wondered if i am missing something important.

any advice appreciated.

No, it’s not fine. The good practice is to separate logic from views.

Let me explain it on example.
Lets say we have a script (model.php) with function which returns blog posts from database:

 function getPosts(){
      //...query the database...
      //...store rows in array...
      return $posts_array;
 }

To show posts on the site we can have another script (controller.php):

 include('model.php');
 $posts = getPosts();
 include('view.php');

You see we don’t output array contents here. We do it in view.php:

 <?php foreach($posts as $post) { ?>
      <div class="post"><?php echo $post['title']; ?></div>
 <?php } ?>

So now you want to ask why should we have 3 files instead of one.
That because we think about the future.
For example, two month later we can decide to add RSS feed to our side.
It’s very simple now. Just slightly modify controller:

 include('model.php');     
 $posts = getPosts();
 $page = $_GET['page'];
 if ($page == 'list'){ include('view.php'); }
 if ($page == 'rss'){ include('rss.php'); }

,and add another view for RSS:

<rss version="2.0">
    <?php foreach($posts as $post) { ?>
        <item><title><?php echo $post['title']; ?></title></item>
    <?php } ?>
</rss>

Now you have all the things on their places.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.