开发者

PHP Undefined Index [duplicate]

This question already has answers here: "Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP (29 answers) Closed 9 years ago.

This is going to sound really stupid, but I cannot figure out why I am getting this error.

开发者_开发技巧

I have created a selection box, named "query_age" in my html form:

<form method="get" action="user_list.php">
<select name="query_age">
  <option value="">Doesn't matter</option>
  <option value="between 18 and 30">18 - 30</option>
  <option value="between 31 and 40">31 - 40</option>
  <option value="between 41 and 50">41 - 50</option>
  <option value="between 51 and 60">51 - 60</option>
  <option value="between 61 and 70">61 - 70</option>
  <option value="between 71 and 80">71 - 80</option>
  <option value="between 81 and 90">81 - 90</option>
  <option value="> 90">Older than 90</option>
</select>

In the corresponding php form, I have:

$query_age = $_GET['query_age'];

When I run the page, I get this error:

Notice: Undefined index: query_age in index.php on line 19

I don't understand why this is happening, and I'd love to know how to make it go away.


I don't see php file, but that could be that -
replace in your php file:

$query_age = $_GET['query_age'];

with:

$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.


The checking of the presence of the member before assigning it is, in my opinion, quite ugly.

Kohana has a useful function to make selecting parameters simple.

You can make your own like so...

function arrayGet($array, $key, $default = NULL)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

And then do something like...

$page = arrayGet($_GET, 'p', 1);


The first time you run the page, the query_age index doesn't exist because it hasn't been sent over from the form.

When you submit the form it will then exist, and it won't complain about it.

#so change
$_GET['query_age'];
#to:
(!empty($_GET['query_age']) ? $_GET['query_age'] : null);


if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜