注意:未定义的索引。我如何定义索引?

时间:2013-10-02 02:04:20

标签: php undefined

我收到了回复:

  

注意:第11行的Page1.php中未定义索引yy

     

注意:第12行的Page1.php中未定义的索引mm

     

注意:第13行的Page1.php中未定义的索引dd

如何定义这些 yy,mm,dd

  <?php 
       $redirect_page= 'Page2.php';

       $_SESSION['yy'] = $_POST['yy'];  // this is on line 11
       $_SESSION['mm'] = $_POST['mm'];  // this is on line 12
       $_SESSION['dd'] = $_POST['dada'];// this is on line 13

      if (isset($_POST['Submit'])) {
          header ('Location: '.$redirect_page);
      }

  ?>

      <HTML>

      <Form name="Page1" action="" method="POST">

      <select name="yy">
      <option value="2001">2001</option>
         // ...Another 100 years
      </select>

       <select name="mm">
       <option value="1">1</option>
       <option value="2">2</option>
         // ... another 10 months
       </select>

       <select name="dd">
       <option value="1">1</option>
       <option value="2">2</option>
          // ...another 29 days
       </select>

        <input type="Submit" name="Submit" value="Submit">
        </Form>
        </HTML>

4 个答案:

答案 0 :(得分:6)

我知道人们已经回答了问题,但我会给你一点建议。使用下面的这个小功能:

function _post($Var, $Default=''){
    return (isset($_POST[$Var]) === TRUE ? $_POST[$Var] : $Default);
}

如果找不到变量,您可以设置默认值。它还将处理未定义的索引错误;)

未定义的索引表示在数组中找不到该条目。在这种情况下,yy数组中不存在条目mmdd$_POST。您必须使用PHP语言构造命令 isset 检查它们是否存在。使用方法如下:

$_SESSION['yy'] = _post('yy', date('Y')); // will be the value of $_POST['yy'] or it not found will be the current year
$_SESSION['mm'] = _post('mm', date('M')); // ... or will be the current month (MM)
$_SESSION['dd'] = _post('dd', date('d')); // ... or will be the current day (DD)

您可以根据需要创建不同的功能:

function _get($Var, $Default=''){
    return (isset($_GET[$Var]) === TRUE ? $_GET[$Var] : $Default);
}

function _session($Var, $Default=''){
    return (isset($_SESSION[$Var]) === TRUE ? $_SESSION[$Var] : $Default);
}

function _put($Var, $Default=''){
    return (isset($_PUT[$Var]) === TRUE ? $_PUT[$Var] : $Default);
}

function _delete($Var, $Default=''){
    return (isset($_DELETE[$Var]) === TRUE ? $_DELETE[$Var] : $Default);
}

function _files($Var, $Default=NULL){
    return (isset($_FILES[$Var]) === TRUE ? $_FILES[$Var] : $Default);
}

答案 1 :(得分:5)

尝试将这些帖子变量包装在isset函数

$_SESSION['yy'] = isset($_POST['yy']) ? $_POST['yy'] : "";  // this is on line 11
$_SESSION['mm'] = isset($_POST['mm']) ? $_POST['mm'] : "";  // this is on line 12
$_SESSION['dd'] = isset($_POST['dada']) ? $_POST['dada'] : "";// this is on line 13

答案 2 :(得分:2)

您必须先启动PHP会话才能设置值:

<?php 
   session_start(); 

   $redirect_page= 'Page2.php';

   $_SESSION['yy'] = $_POST['yy'];
   $_SESSION['mm'] = $_POST['mm'];
   $_SESSION['dd'] = $_POST['dada'];

   // rest of code
?>

答案 3 :(得分:1)

if(isset($_POST['yy']))
    $_SESSION['yy'] = $_POST['yy'];
if(isset($_POST['mm']))
    $_SESSION['mm'] = $_POST['mm'];
if(isset($_POST['dd']))
    $_SESSION['dd'] = $_POST['dd']; // assuming it is $_POST['dd'] and not $_POST['dada']