2017-12-27 145 views
-2

我有一個包含無線電輸入的表單。無線電輸入可以是0,1或選擇enot。我正在嘗試進行輸入驗證,以確保值在發佈到數據庫之前僅爲0,1或空。不知怎的,下面的代碼不起作用。空無線電輸入驗證

有人可以幫我嗎?

$posttodatabase = true; 
$array = (0, 1); 
if (!in_array($_POST['x'], $array) && isset($_POST['x'])) { 
    $posttodatabase = false; 
}; 

編輯:所附表格:

 <form action='registration.php' method=POST> 
      <input type="radio" name="x" value=0> Foo 
      <input type="radio" name="x" value=1> Bar 
      <input class="button" type=submit value='Submit'> 
     </form> 
+0

更新您的問題,包括在HTML /形式。 –

+0

你應該在表格中引用所有內容,這可能會對你有所幫助。無論哪種情況,下面都有幾個答案。 –

回答

1

不要設置$posttodatabase默認true並將其更改爲false時,不符合要求。當需求滿足(值存在且是預期值之一)時,反過來使用它來確保只將值設置爲true

$posttodatabase = false; 
if (!isset($_POST['x']) OR     // is not set OR 
    (
     isset($_POST['x']) AND    // is set and... 
     in_array($_POST['x'], array(0, 1)) // ... one of these values 
    )) { 
    $posttodatabase = true; 
} 

(或直接賦值...)

+0

不幸的是,這並沒有捕獲空的無線電值(當未指定任何選項時發生)。我該如何解決這個問題? – StudentAsker

+0

@StudentAsker沒有選擇是一個有效的選項/「輸入」? – Progman

+0

這是正確的。 – StudentAsker