PHP for循环错误未定义的偏移量

时间:2010-12-08 12:07:07

标签: php loops

我有下面的代码循环选中的复选框并执行和sql语句。

if (isset($_POST['delete']))
{
   for($i=0;$i<$recordcount;$i++)                       
   {                        
       $deleteid = isset($_POST['checkbox'][$i]);
       echo "ID = ".$deleteid."<br />"; //Error checking
       $sqldelete = "DELETE FROM customer WHERE cus_ID = ".$deleteid."";
       echo $sqldelete."<br />"; //Error checking
       $deleters = $conn->Execute($sqldelete);                  
   }
}

这会运行sql查询,但它会尝试运行它超过所需的次数,即我检查两个复选框,sql运行3次。因此ID为空时会出现错误。我也得到一个未定义的偏移量1。

有什么建议吗?谢谢。

3 个答案:

答案 0 :(得分:3)

这一行肯定是错的:

$deleteid = isset($_POST['checkbox'][$i]);

也许你的意思是这样的?

$deleteid = isset($_POST['checkbox'][$i]) 
    ? intval($_POST['checkbox'][$i]) : false;
if ($deleteid === false) {
    continue;
}

// rest of the code follows

此外,您可能可以摆脱$recordcountforeach超过$_POST['checkbox']

答案 1 :(得分:2)

if (isset($_POST['delete']))
{
   for($i=0;$i<$recordcount;$i++)                       
   {                        
       $deleteid = isset($_POST['checkbox'][$i]);
       if ($deleteid) {
          $sqldelete = "DELETE FROM customer WHERE cus_ID = ".$_POST['checkbox'][$i];
          echo $sqldelete."<br />"; //Error checking
          $deleters = $conn->Execute($sqldelete);                  
       }
   }
}

为了安全而逃避你的输入

答案 2 :(得分:0)

试试这个

if(isset($_POST['delete']))
    {
       $i=0;
        foreach($_POST['checkbox'] as $user)
        {
            $sqldelete = "DELETE FROM customer WHERE cus_ID = ".$user."";
           echo $sqldelete."<br />"; //Error checking
         $deleters = $conn->Execute($sqldelete); 
            $i++;
        }

    }