Use PHP To Display Page Content (LMAWT part 2)

Use PHP To Display Page Content (LMAWT part 2)

If you missed the previous posts, you can read the Introduction and First part to catch with us.

What we are going to do today is make our links work and display the content depending on what link we click.

First let’s make our links go live. In our final result of part 1, our links were dead. To make a link work, we must use this syntax:

<a href="./">Home</a>
<a href="./?news">News</a>
<a href="./?contact">Contact</a>
*** notice we use ?news for the news, ?contact for the contact page etc, will be explained later ***

So let’s change all of our links to this. Our final result will be this. As you can see, the links are underlined and you can click on them. But if you click on them you will notice nothing really changes on the page, except for the URL in the browser.. that’s because we need our PHP code that will “read” the URL and display the content that comes along.

Let’s see the PHP code that we put into our #main-content div. To load different contents depending on what click we link on, we are going to use the switch function, which is not hard to understand, is very useful and works fast!

<?php
switch (key($_REQUEST)) {

	case 'news':
		echo 'We will display our news here';
	break;

	case 'members':
		echo 'This will be the member list';
	break;

	// we continue like this for all our links
	// and finish with the default statement

	default:
	echo 'Welcome to my first website';

}
?>

As I said before, put this code between inside your #main-content DIV.

<div id=”main-content”>
<?php switch () {} ?>
</div>

What will this piece of code do?
It will display different contents based on the page we are on. If, for example, we will click on our “news” link, the URL will change to “domain.com/?news” and the content that will be shown will be “news.php“, because of the ‘case’ we wrote. In this case, what comes after the question mark in the URL is called a “query string” and we will work with these.

In this example we are using the “key($_REQUEST)” but we could change this to react to something like “domain.com/?page=news” and in this case we would use a different switch. Tell me if you want to know about it and I’ll write an example for this.

Anyway, check what we accomplished now. We made our first working website, we could actually put whatever we would like inside, we are done. The content is changing and everything is working fine.

Any questions? Feel free to ask!

If you liked this post think about subscribing to my RSS feed and prevent missing anything interesting. It's free, fast and doesn't hurt. Promise. Click here.
Related posts: