Page 1 of 1

Organising Database Access

Posted: Mon Sep 07, 2009 4:59 am
by cusimar9
I'm putting together a PHP site with MySql and I've come across something I've not had to deal with before in PHP.

I use 'includes' quite a bit as it makes my code easier to maintain. So, as an example:

Code: Select all

 
<?php
    mysql_connect();
        // Do my DB access here
    mysql_close();
?>
<html>
<body>
 
    <?php include "leftbar.php" ?>
 
    <div id="content">...</div>
 
    <?php include "rightbar.php" ?>
 
    <?php include "footer.php" ?>
 
</body>
</html>
 
This is fairly straightforward, but I've now got a bit of a situation that the leftbar and rightbar includes require something from the database, say $resultA and $resultB.

What I'm currently doing is retrieving $resultA and $resultB at the top of every page where I do my DB access. But this really messy. Pages that shouldn't do any DB access at all (i.e. the 404 page or the Contact page) still have to connect to the DB to retrieve these $resultA and $resultB values.

I also can't allow the leftbar and rightbar to retrieve their own resultsets because that would mean either a) open up 2 seperate connections to the database or b) close the database at the bottom of every page, which as I understand is also not a good idea.

They're not big resultsets, and in ASP I would just load them into an Application variable and use that every time rather than opening up a new connection. However PHP doesn't have Application variables. I could load them into the Session but then search engines wouldn't be able to read the content.

Can anyone recommend a good way to approach this sort of scenario?

Re: Organising Database Access

Posted: Thu Sep 10, 2009 4:24 pm
by cusimar9
Okay thanks I'll do that :)