php 中的未定义索引(我已经搜索了整个互联网和堆栈溢出,几乎尝试了所有内容)


Undefined Index in php (I've searched all over internet, and stackoverflow, tried almost everything)

可能的重复项:
PHP:"注意:未定义的变量"和"注意:未定义的索引"

enter code here这是PHP代码

$choice_spc_port = $_POST["txtSpace"];  (THIS LINE GIVES UNDEFINED INDEX NOTICE)
$choice_loc = $_POST["txtLocation"]; (THIS LINE GIVES UNDEFINED INDEX NOTICE)

这是HTML表单

<form id="animalform" name="animalform" method="post" action="animalform.php">
<div  class="wrapper"> <strong><span>*</span> Text Space portion:</strong>
            <div class="formText">
              <input type="radio" name="txtSpace" value="HR"/>Text space for Horse.<br />
      <input type="radio" name="txtSpace" value="ZB"/>Text Space For Zebra<br />
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Animal Location:</strong>
                <div class="formText">
                <input type="radio" name="txtLocation" value="txtSetXY"/> Specify Animal Location<br />
                    <div style="padding-left:20px;">
                    X: <input type="text" id="locField" name="txtXLocation">  <span>Taking (x=1,y=1) top left box. Increment +1 in value of X moving right</span><br />
                    Y: <input type="text" id="locField" name="txtYLocation">  <span>Taking (x=1,y=1) top left box. Increment +1 in value of Y moving downwards</span><br />
                    </div>
                    <input type="radio" name="txtLocation" value="Default"/>Default
                </div>
            </div>
</div>

要插入到数据库中的查询

$insert = "INSERT INTO dbForm (db_space_portion, db_animal_location) VALUES ('{$choice_spc_port}', '{$choice_loc}')";

我在 Firefox 中尝试了相同的方法,这两行给出了括号中提到的通知。同样在互联网上,许多人正在寻找解决方案。所以我认为这个问题会对很多人有所帮助。

此错误

显示在较新版本的PHP中。

有多种方法可以消除错误:

  1. 您可以为此使用错误抑制方法
  2. 检查变量是否不为空或将其设置为 0,例如 choice_spc_port=0在开始时
  3. 伊塞特方法也很好用

使用此查询。

if(isset($_POST['txtSpace'])) {
    $choice_spc_port = $_POST['txtSpace'];
}
if(isset($_POST['txtLocation'])) {
    $choice_loc = $_POST['txtLocation'];
}
$insert = mysql_query("INSERT INTO dbForm (db_space_portion, db_animal_location) VALUES ('{$choice_spc_port}', '{$choice_loc}')");

为此使用isset,当$_POST['txtSpace']$_POST['txtLocation']为空且未设置时,它不会给您未定义的索引通知。

if(isset($_POST['txtSpace']))
{
     $choice_spc_port = $_POST["txtSpace"];  
}
if(isset($_POST['txtLocation']))
{  
     $choice_loc = $_POST["txtLocation"];
}

这样做可以获取任何 Post 变量:

if(isset($_POST['txtSpace'])){$choice_spc_port = $_POST["txtSpace"];}
if(isset($_POST['txtLocation'])){$choice_loc = $_POST["txtLocation"];}

对于您的SQL句子:

$insert = "INSERT INTO dbForm (db_space_portion, db_animal_location) VALUES ({'$choice_spc_port'}, {'$choice_loc'})";