Simple Question: Using page url to determine content of page?

Hi all, this one’s been bothering me for a while and I think would really streamline my php development.

Basically I see loads of sites with the vague code “index.php?page=home” where the “page=home” determines the content of the page, with everything else being an outside template (probably stored in index.php).

My thinking was it was a conditional statement basically saying, if the page url contains the word home, then run this script etc… but I can’t figure it out!?

Should be simple for some of you, just looking for the best practice on this one and a tutorial :slight_smile:

Hi, you are pretty much there :slight_smile:

The $_GET[‘page’] variable can be used to then query a database or load a flatfile page

$page = isset($_GET['page']) ? $_GET['page'] : 'default';
// if the page=home variable is set then store it in a simple variable

$sql = mysql_query("select content from dbtable where pagename = '". mysql_real_escape_string($page) ."'");
// query the database and get the information

then use mysql_fetch_assoc($sql); to assign the database info and echo it onto the page

$rows = mysql_fetch_assoc($sql);

echo $rows['content'];

That gives you the basic plan :slight_smile:

Here you go. :wink:

#define all available page options
$pages = array(
    #name              #file where content stored
    'home'          => '',
    'about-us'      => '',
    'contact-us'    => '',

#if a page is requested and it is valid, use it, else use home as default
$page = ( !empty($_GET['page']) && array_key_exists($_GET['page'], $pages) ) ? $_GET['page'] : 'home' ;
        <!-- include content -->
        <?php include($pages[$page]); ?>

Feel free to ask away.

Thanks a lot for the help, both great answers but I think Anthony’s is closest to my needs as I have a lot of content on the pages!

Anthony, would the link example which I supplied coupled with your code yield the correct results?

It would. (or should! :p)

Linked to your observation is some mod_rewrite magic that makes:

site .com/home

rewrite to (ie serve content from)

site .com/index.php?page=home

So there is probably more wide-scale use of these methods than you had previously thought.

And what is more, some urls similar to those, such as :

site .com/article/my-moms-mad

rewrite to:

site .com/article.php?slug=my-moms-mad

which in turn get data from a database table whose schema may resemble;


slug | my-moms-mad
title | “My Mom’s mad”
intro | “She looks pretty normal, but she’s vegan …”
content| "a loada content … "