2017-04-02 23 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(); 

}