2017-04-02 55 views
1

我有3个文本字段和一个隐藏字段。文本字段接受日期。如果输入的日期晚于今天的任何文本字段,则应显示错误消息。如果我在第一个文本字段中输入更晚的日期,这只能正常工作。如果我在第二个或第三个这样做,它会继续进行重定向,这显然不应该发生。表单验证不能与FOR循环配合使用

$count = count($_POST['complete_date']); 
     for($i = 0; $i < $count; ++$i) { 

     if($_POST['complete_date'][$i] > date('Y-m-d')) { 
      echo error_message("Date can't be in the future"); 
      break; 

      } else { 


$stmt = $link->prepare("UPDATE `units` SET `complete_date` = ? WHERE `units` = ?"); 
     $stmt->bind_param("si", $_POST['complete_date'][$i], $_POST['units'][$i]); 
     $stmt->execute(); 
     $stmt->close(); 
     header("location: dashboard.php"); 
     exit(); 

    } 
} 

回答

1

这很正常,如果您在第二或第三位置有错误,您仍然对数组的第一项执行查询。你应该这样做:

$count = count($_POST['complete_date']); 
$error = false; 
    for($i = 0; $i < $count && ! $error; ++$i) { 

    if($_POST['complete_date'][$i] > date('Y-m-d')) { 
     echo error_message("Date can't be in the future"); 
     $error = true; 

     } 
    } 

    //Only process if there are no errors in all the dates 
    if(! $error){ 
    $stmt = $link->prepare("UPDATE `units` SET `complete_date` = ? WHERE `units` = ?"); 
    $stmt->bind_param("si", $_POST['complete_date'][$i],$_POST['units'][$i]); 
    $stmt->execute(); 
    $stmt->close(); 
    header("location: dashboard.php"); 
    exit(); 

}