Jump to content


Dynamic URLS


4 replies to this topic

#1 Nick

    Young Padawan

  • Members
  • Pip
  • 118 posts
  • Gender:Male

Posted 10 December 2006 - 10:22 AM

I'm new to php and I want to make dynamic urls on my website (the ones that are like index.php?page=1). I tried writing my own, but the problem is I don't know php. It works if I don't use the "else" statement at the end, but I want the else statement at the end so if the page is now found the else will echo "404 error" or something of that. I searched google and pixel2life and couldn't find anything about dynamic urls. All I find is how to use mod rewrite to make the dynamic urls look static.

Here is my code:
<?php 
   if($page == 1)
   echo('This is page 1');
			
   elseif($page == 2)
   echo('This is page 2');
?>

Thanks ;)

Edited by Nick, 10 December 2006 - 10:23 AM.


#2 someguy

    Young Padawan

  • Members
  • Pip
  • 14 posts

Posted 10 December 2006 - 10:31 AM

Try...

<?php

$page = $_GET['page'];

if($page == "1"){ echo("This is page 1"); }
elseif($page == "2"){ echo("This is page 2"); }

?>


#3 cheerio

    Young Padawan

  • Members
  • Pip
  • 246 posts
  • Gender:Male

Posted 10 December 2006 - 10:32 AM

This is the if/elseif/else way.
<?php
$page = $_GET['page']; //This is important..

if( $page == 1 )
{ //Brackets like these make code easier to read in my opinion
  echo 'This is page 1';
}
elseif( $page == 2 )
{
  echo 'This is page 2';
}
else
{
  //If there is no selected page...
  echo 'This is the default page!';
}
?>
This is how you can do it using the switch statement. Switch is basically if/elseif/else but looks different ;)
<?php
$page = $_GET['page'];
switch( $page )
{
  case 1;
  echo 'This is page 1!';
  break;

  case 2;
  echo 'This is page 2';
  break;

  default;
  echo 'This is the default page';
  break;
}

Edited by cheerio, 10 December 2006 - 10:32 AM.


#4 Nick

    Young Padawan

  • Members
  • Pip
  • 118 posts
  • Gender:Male

Posted 10 December 2006 - 11:28 AM

Thanks for all the replys ;)

#5 Chaos King

    Senior Programmer

  • P2L Staff
  • PipPipPip
  • 676 posts
  • Gender:Male
  • Location:Florida

Posted 10 December 2006 - 06:39 PM

Switch statements are the best way to go like what cherrio said above.

$page = $_GET['page'];

switch ( $page )
{
	default:
		echo 'Welcome to the main page.';
	break;
	
	case 'about':
		echo 'More to learn about who I am.';
	break;
	
	case 'contact':
		echo 'Email me if you have to.';
	break;
}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users