Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I define index?

Tags:

php

index.php contains links in this style:

<a href="index.php?id=1">1</a>
<a href="index.php?id=2">2</a>

and then a PHP passage in this style:

if ($_GET["id"] == "1") {}
elseif ($_GET["id"] == "2") {}

So when a link is clicked, the page is reloaded, and one of the if/elseif blocks is run.

However, when I load index.php the first time I get this error: Undefined index: id

I guess this means that $_GET["id"] needs to have a default value. But where do I put this default value in my code? If I give it, for example, the value "0" in the beginning of the script, the code blocks will never run, since the value keeps being reset on every reload.

like image 620
Johanna Avatar asked Dec 27 '22 00:12

Johanna


1 Answers

You can first check to see if it has been set:

if (isset($_GET["id"])) {

    if ($_GET["id"] == "1") {

    } elseif ($_GET["id"] == "2") {

    }

}

isset is a language construct which will not issue any errors if the variable isn't set.

empty also won't issue errors but also checks for a "non-empty" value.

like image 126
webbiedave Avatar answered Jan 11 '23 22:01

webbiedave