PHP新手求教:关于GET,总是出现Notice:Undefined index。希望给出具体解决做法。

运行时会出现:

Notice: Undefined index: food in C:\xampp\htdocs\php\check.php on line 7

代码:

<html>
<head>
<title>Using Default Checkbox</title>
</head>
<body>
<?php
$food=$_GET['food'];
if (!empty($food))
{
echo "The foods selected are:<strong>";
foreach($food as $foodstuff)
{echo '<br/>'.htmlentities($foodstuff);
}
echo "</strong>.";
}
else {
echo ('
<form action=".htmlentities($_SERVER[/"PHP_SELF/"])." method="GET">
<fieldset>
<label>
Italian <input type="checkbox" name="food[]" value="Italian"/>
</label>
<label>
Chinese <input type="checkbox" name="food[]" value="Chinese" checked="checked"/>
</label>
<label>
Mexican <input type="checkbox" name="food[]" value="Mexican"/>
</label>
</fieldset>
<input type="submit" value="Go!" />
</form>');
}
?>
</body>
</html>

还有一个问题代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- @(#) $Id$ -->
<head>
<title>Building a Form</title>
</head>
<body>
<?php
$search=htmlentities($_GET['search']);
$self=htmlentities($_SERVER['PHP_SELF']);
if ($search === '')
{ echo ('
<form action=".self." method="GET">
<label>
Search:<input type="text" name="search" />
</label>
<input type="submit" value="Go!" />
</form>');
}
else {echo "The search string is:<strong>$search</strong>";}
?>
</body>
</html>
运行后,框中输入以后,点击GO,进入的页面显示Object not found!
The requested URL was not found on this server. 还是不懂是怎么一回事。我输入的是教材上原文,用的Localhost,连接等也没有问题。 请高人指教。

首先,这个不是错误,是warning。所以如果服务器不能改,每个变量使用前应当先定义。
方法1:服务器配置修改
修改php.ini配置文件,error_reporting = E_ALL & ~E_NOTICE
方法2:对变量进行初始化,规范书写(比较烦琐,因为有大量的变量)。但还没有找到好定义方法,望大家指教
方法3:每个文件头部加上:error_reporting(0); 如果不行,只有打开php.ini,找到display_errors,设置为display_errors = Off。以后任何错误都不会提示。
方法4 :做判断:isset($_GET["page"]) if-else判断
或者加上'@'表示这行如果有错误或是警告不要输出
如:@$page=$_GET["page"]
方法5:file1.php文件把$xx变量付一个值,用post 传递给file2.php,
如果file2.php没有$xx的定义,而直接使用$yy=$xx; 系统就会报错:"undifined variaable $xx", 如果file2.php的文件开始用$xx="";定义,那么file1.php的$xx值就传不过来了!
file2.php里可以这样
if(!isset($xx)) $xx="";追问

我最想知道的是第二个问题

追答

第二个问题出在里面的这个.self. ,把.self.去掉是请求当前页,或者替换为其他你要请求的url地址

参考资料:http://shuai.be/archives/php-undefined-index/

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-07-22
1、你的post值中没有food这个键值,你在页面上的name是food[];
2、<form action=".self." method="GET">这句中的action应该是你要提交的页面地址,追问

能帮忙把第二个问题解释清楚一些吗? 第二个问题里,书上讲,在搜索框中输入"PHP",然后go,得到的显示是"The search string is:PHP",但我是object not found

第2个回答  2012-07-22
$food = isset($_GET['food']) ? $_GET['food'] : '';
第3个回答  2012-07-23
$food=@$_GET['food'];

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网