-1

So I was working on php navigation using index.php?id=MYID. I used some random website to learn the code. and it is here

I made my program worked successfully, I mean that it is navigating users to other pages successfully. But it is showing some kind of error. which is

Notice: Undefined index: id in C:\xampp\htdocs\php_tests\index.php on line 17

I tried everything out. It is my first question here so I may not be able to clear my self so I also request my mentors to guide me if there is anything wrong in my question and also answer my question. My code is below:

<table width="125" cellpadding="0" cellspacing="0" style="display:inline;">
   <tr>
      <td><a href="index.php?id=main" target="_self" name="main">Home</a></td>
   </tr>
   <tr>
      <td><a href="index.php?id=News" target="_self" name="news">News</a></td>
   </tr>
   <tr>
      <td><a href="index.php?id=MoreInfo" target="_self" name="MoreInfo">MoreInfo</a></td>
   </tr>
</table>
<div id="section" style="height:500px; width=:auto; background-color:#CCC">
   <?php
      $id = $_REQUEST['id']; // this will get the id of the link, this will be explained later.

      switch($id) { // make a case with the id
      default: include('main.php'); //When page is loaded this will be the main content, put the content in main.php(you can change the name)
      break; // close this case

      case "News": include('news.php'); // The content in news.php will be called when id=News
      break; // close this case

      case "MoreInfo": include('MoreInfo.php'); // The content in MoreInfo.php will be called when id=Members
      break; // close this case


      } // close switch
      ?>
</div>
PRVS
  • 1,612
  • 4
  • 38
  • 75

1 Answers1

0

You need to check if value is set or not like:

<?php
$id = ''; // define as empty in default
if(isset($_REQUEST['id'])){
    $id = $_REQUEST['id'];
}
?>

Also keep in mind, if you not set $id as empty in default than you will again get undefined variable notice for $id.


From PHP Manual:

isset — Determine if a variable is set and is not NULL

devpro
  • 16,184
  • 3
  • 27
  • 38
  • Ok...I a added a code to check if variable is set or not. It checks successfully but this time, it vanishes my main.php content which is to be loaded on default index.php. – Mohammad Abbas Feb 02 '16 at 09:28
  • @MohammadAbbas: abbas, when u use MYID it will include the main.php file only that u defined in default. – devpro Feb 02 '16 at 09:43