Jump to content

Getting variables from url


Recommended Posts

I have a site that passes variables through the url so the site can pull up the right page. My url looks like this

 

index.php?page=products

 

and when i go there it displays a page that says products

 

when i go to

 

index.php?page=products&id=1

 

it displays a page that says monitors

 

but if i go here

 

index.php?page=products&id=2

 

or any other number it keeps going to the page that says monitors

 

what am i doing wrong

 

<?php

if (isset($_GET['id']) == 1) {
	echo '<h3>Monitors</h3>';
}
elseif (isset($_GET['id']) == 2) {
	echo '<h3>Desktops</h3>';
}
elseif (isset($_GET['id']) == 3) {
	echo '<h3>Notebooks</h3>';
}
elseif (isset($_GET['id']) == 4) {
	echo '<h3>Netbooks</h3>';
}
elseif (!isset($_GET['id'])) {
	echo '<h3>Products</h3>';
}	

?>

Link to comment
https://forums.phpfreaks.com/topic/200832-getting-variables-from-url/
Share on other sites

Wrong use of isset is your problem.  Using isset checks if the variable has been set, not what is actualy in it.  you're close, just tweek it to this and you should be fine

<?php
if (isset($_GET['id'])) {
if ($_GET[id] == 1){
echo '<h3>Monitors</h3>';
}
elseif ($_GET['id'] == 2) {
echo '<h3>Desktops</h3>';
}
elseif ($_GET['id'] == 3) {
echo '<h3>Notebooks</h3>';
}
elseif ($_GET['id'] == 4) {
echo '<h3>Netbooks</h3>';
}
}
else {
echo '<h3>Products</h3>';
}
?>

Your "if" statement is incorrect.

 

It should be

<?php
if (isset($_GET['id']) && $_GET['id'] == 1) {
	echo '<h3>Monitors</h3>';
}
elseif (isset($_GET['id'])  && $_GET['id'] == 2) {
	echo '<h3>Desktops</h3>';
}
elseif (isset($_GET['id'])  && $_GET['id'] == 3) {
	echo '<h3>Notebooks</h3>';
}
elseif (isset($_GET['id'])  && $_GET['id'] == 4) {
	echo '<h3>Netbooks</h3>';
}
elseif (!isset($_GET['id'])) {
	echo '<h3>Products</h3>';
}	

?>

 

A better way to do this (IMHO) would be to either use an array to store what is to be printed (good way to check for errors) or to use a switch statement:

 

Using an array:

<?php
$val_id = array('Products','Monitors','Desktops','Notebooks','Netbooks');
$id = (isset($_GET['id']) && $_GET['id'] > 0 && $_GET['id'] < 5)?$_GET['id']:0;
echo '<h3>' . $val_id[$id] . '</h3>';
?>

 

Using a switch:

<?php
$out = 'Products';
if (isset($_GET['id'])) {
   switch($_GET['id']) {
      case 1:
         $out = 'Monitors';
         break;
      case 2:
         $out = 'Desktops';
         break;
      case 3:
         $out = 'Notebooks';
         break;
       case 4:
         $out = 'Netbooks';
         break;
       default:
          $out = 'Products';
     }
   }
echo '<h3>' . $out . '</h3>';
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.