Notice: Undefined index: news

Discussion in 'PHP' started by zaay, Aug 7, 2009.

  1. #1
    Hello all ! ;)

    I build simple news script for myself.. On news.php i have this code:
    switch($_GET['news']) {
            default:
            displayNews();
            break;
        case 'show':
            displayOneItem($_GET['id']);
            break;
        case 'all':
            displayNews(1);
            break;
        case 'addcomment':
            addComment($_GET['id']);
    }
    PHP:
    Error im getting:

    Notice: Undefined index: news

    Why is that.. I defined default switch for it .. And i can see news, just this error on header..

    Thaanx!
     
    zaay, Aug 7, 2009 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Your referencing $_GET['news'] when $_GET['news'] has not been set.

    You could do something like this to supress the error, or just leave it alone.
    
    if(!isset($_GET['news']))
    {
    $_GET['news'] = null;
    }
    
    switch($_GET['news']) {
        case 'show':
            displayOneItem($_GET['id']);
            break;
        case 'all':
            displayNews(1);
            break;
        case 'addcomment':
            addComment($_GET['id']);
    break;
    default:
            displayNews();
    }
    
    PHP:
    Also, it's generally a good idea to leave default: at the bottom of the switch statement as a catch all. Otherwise if you forget to add break, the script does not work correctly.
     
    jestep, Aug 7, 2009 IP
  3. zaay

    zaay Member

    Messages:
    269
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    30
    #3
    Hello ! ;)

    Thanx for this, it works very very well ! ;) Thanx!

    Now it's working, but i don't really know what you did with taht code.. Do you have5 minutes, to explain me this please ? :)

    Thank you !
     
    zaay, Aug 7, 2009 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    Let's say you access your website without any parameters in the url. IE: mysite.com.

    In this case: $_GET['news'] is not set, so trying to reference it in any way, such as a switch statement, will throw a warning.

    What the !isset does, it look to see if the $_GET['news'] variable is set, and if not, it sets the $_GET['news'] variable to null. A null value is technically nothing, but will still allow $_GET['news'] to be referenced without an error or warning.
     
    jestep, Aug 7, 2009 IP
  5. zaay

    zaay Member

    Messages:
    269
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    30
    #5
    Oh i see ! ;) Thank you very much ! ;)
     
    zaay, Aug 7, 2009 IP