Help with querystring error.

I am try to pass a query string to the same page but having problem
This is my code:

<HTML><BODY>
   <div align=center>
   <A href="?page=1">Page 1</A> -
   <A href="?page=2">Page 2</A> -
   <A href="?page=3">Page 3</A>
   </div><hr>
<? switch($page) {
     case "1" :?>
        THis is page one
<? break; case "2" :?>
        This is page two
<? break; case "3" :?>
        This is page three
<? break; default:?>
        This is the default page
        ?}
?>
</BODY></HTML>

Why am I having the following error:

Notice: Undefined variable: page in c:\inetpub\wwwroot\ex1\qstring.php on line 7

I appreciate any help

thanks

tip

Edited 3 Years Ago by happygeek: fixed formatting

<HTML><BODY>
<div align=center>
<A href="">Page 1</A> -
<A href="">Page 2</A> -
<A href="">Page 3</A>
</div><hr>
<? switch($page) {
case "1" :?>
THis is page one
<? break; case "2" :?>
This is page two
<? break; case "3" :?>
This is page three
<? break; default:?>
This is the default page
<? } ?> 
</BODY></HTML>

You forgot to put "<" at this "<? } ?>"

That is not the problem, at least with regard to the error specified. The problem is that you think that by visiting mysite.php?page=2, the variable $page will be set to 2. In the majority of circumstances (default since PHP 4.0.2, I believe), this (fortuantely, from the side of security) is false.

If you want to retrieve the variable page from your URL string, you need to access it with $_GET. So, while PoA is correct in noticing the missing <?php } ?> towards the end of your script, you also need to change

switch( $page ) {

to

switch( $_GET['page'] ) {

(Although, it's odd that the script should run at all - as it is apparently doing to produce a notice rather than a parse error - if there was a missing closing brace.)

Thank you very much Roberdin and poA for your help. Now I can proceed

tip

should really have a break after the default: and before }
and no real need to use _GET with $page cos switch works on gets anyways :x

Sorry, what? I'm not quite sure what you mean there.

Unless your PHP.ini file has been explicitly modified to do this (register_globals = on), $_GET will NOT be the same as $page. $_GET is an array, containing the URI-passed values.

So, if you visit blah.php?foo=bar&bob=42

Then $_GET will equal 'bar', and $_GET will equal 42. $foo and $bob will be undefined; as $page was in Tip's original code.

This question has already been answered. Start a new discussion instead.