2012-09-20 139 views
2

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”未定义指数

我学习PHP和我已经使用POST方法提交表单数据,我不知道为什么我得到这两个错误:

Notice: Undefined index: search_for in \xampp\htdocs\samir\indexes.php on line 5

Notice: Undefined index: replace_with in \xampp\htdocs\samir\indexes.php on line 6

if(isset($_POST['user_input']) && isset($_POST['search_for']) && isset($_POST['replace_with']) 
    && !empty($_POST['user_input']) && !empty($_POST['search_for']) && !empty($_POST['replace_with'])) 
    echo $user_input = $_POST['user_input']; 
    echo $search_for = $_POST['search_for']; 
    echo $replace_with = $_POST['replace_with']; 
+2

某些代码可能? –

+1

你能告诉我们你的代码吗? –

+0

我们需要看你的代码! – simonlchilds

回答

1

当使用$ _POST$ _GET从表单中检索变量时,可能会遇到此错误:

注意:未定义索引的字段'正在执行的'php'文件路径'当前行'

由于您的PHP错误报告设置而出现此错误。通常,当你的变量没有正确设置时出现。有两种方法可以解决这个问题:

1.检查在使用前是否设置了$_POST['action']$GET['action']。例如:

if (!isset($_POST['action'])) {//your pure stuff }  

if (!isset($_GET['action'])) {//your pure stuff } 

2.禁止通知警告

通知警告可以通过在你的php.ini改变使用error_reporting变量被抑制。使用error_reporting可以设置为显示除了那些通知所有错误和编码标准警告:使用error_reporting = E_ALL &〜E_NOTICE

<?php error_reporting (E_ALL^E_NOTICE); ?> 

,但我个人的建议是解决了警告,而不是使用2方法


更新问题答案

你还没有添加封闭括号{}所以只有一个行,如果以后会考虑在我F主体和您的第二和第三回声将被执行是否结果你如果是真的还是假的

应该

if(isset($_POST['user_input']) && isset($_POST['search_for']) 
    && isset($_POST['replace_with']) && !empty($_POST['user_input']) 
    && !empty($_POST['search_for']) && !empty($_POST['replace_with'])) { 
    echo $user_input = $_POST['user_input']; 
    echo $search_for = $_POST['search_for']; 
    echo $replace_with = $_POST['replace_with']; 
} 
3

你忘了添加封闭括号内为您if声明,就像这样:

if(isset($_POST['user_input']) && isset($_POST['search_for']) 
    && isset($_POST['replace_with']) && !empty($_POST['user_input']) 
    && !empty($_POST['search_for']) && !empty($_POST['replace_with'])) { 
    echo $user_input = $_POST['user_input']; 
    echo $search_for = $_POST['search_for']; 
    echo $replace_with = $_POST['replace_with']; 
} 

上面的代码应该做你想做的。

+1

只是为了澄清,没有括号括起来,只有'if'语句后的第一个命令被视为有条件的 - 所以你的第二个和第三个回声将被执行,无论你的'if'的结果是真还是假 – Basic

+0

非常感谢非常有帮助 – user1481225

+0

不客气! :-) – Nelson

1

如果您在发布表格之前使用变量,例如$var = $_POST['var']; 它将返回一个错误。

最好检查提交按钮是否被按下。

例子:

if(isset($_POST['submit'])){ 
    //form has been posted 
} 

然后,我将确保所有的变量后,你将使用设置,如果没有抛出异常。

例子:

$error = false; 
//['submit'] is the button used to post the form. 
if(isset($_POST['submit'])){ 
    $testVar = (isset($_POST['testVar']) && strlen($_POST['testVar']) > 0 ? $_POST : $error[] = 'Please enter something.'); 

    if(!$error){ 
     //Submit for 
    } 
    else{ 
     foreach($error as $e){ 
      echo $e; 
     } 
    } 
}