2016-01-24 20 views
0

HTML標記:如何獲得由父類名元素在PHP

<form> 
    <div class="required"> 
    <input id="name" name="name"> 
    </div> 
    <div class="required"> 
    <input id="email" name="email"> 
    </div> 
    <div class="non-required"> 
    <input id="other" name="other"> 
    </div> 
    ... 
    alot of input here 
    ... 

</form> 

PHP:

<?php 

extract($_POST, EXTR_PREFIX_ALL, 'input'); 

if (empty($input_name) || empty($input_email) || empty($input_other) || ... alot of input here...) { // i want only the input that has `required` class in this line 
    // main function here 
} 

?> 

我可以手動編輯,但如何自動可以選擇inputrequired類的PHP主功能?

謝謝。

回答

2

您無法訪問父級的名稱。用戶提交表單時不會傳輸此信息。

$ _POST中唯一可用的信息是輸入元素的名稱和值。你可以定義你的輸入元素的名稱來表示需要這樣的需要/非:

<form> 
    <div class="required"> 
     <input id="name" name="required[name]"> 
    </div> 
    <div class="required"> 
     <input id="email" name="required[email]"> 
    </div> 
    <div class="optional"> 
     <input id="another" name="optional[another]"> 
    </div> 
    <div class="required"> 
     <input id="other" name="required[other]"> 
    </div> 
</form> 

使用這個模式,你將有兩個子陣列,$ _ POST,取名必需和可選:

Array //$_POST 
(
    [required] => Array 
    (
     [name] => value, 
     [email] => value, 
     [name] => value 
    ), 
    [optional] => Array 
    (
     [another] => value 
    ) 
) 

警告
如果您使用此解決方案,請確保您正確驗證輸入。您將信任用戶代理以提供有關這些字段的正確信息。查看Trincot對純服務器端解決方案的回答。

+0

非常好的解決方案! – trincot

+0

@trincot:謝謝你的讚揚。你的解決方案遵循同樣的想法,但保持一切服務器端。根據情況,這可能會更快,更安全。因此我在我的問題中增加了一個附錄。 – PvB

2

由於您自己生成HTML,因此您實際上知道哪些輸入元素具有類「必需」。所以我會建議你首先用必要的字段創建一個數組,然後用動態類的值生成HTML。

然後以後就可以使用相同的數組,以檢查空虛:

HTML代:

<?php 
// define the list of required inputs: 
$required = array("name", "email"); 

// define a function that returns "required" or "non-required" 
// based on the above array. 
function req($name) { 
    global $required; 
    return in_array($required, $name) ? 'required' : 'non-required'; 
} 
// Now generate the classes dynamically, based on the above: 
?> 
<form> 
    <div class="<?=req('name')?>"> 
    <input id="name" name="name"> 
    </div> 
    <div class="<?=req('email')?>"> 
    <input id="email" name="email"> 
    </div> 
    <div class="<?=req('other')?>"> 
    <input id="other" name="other"> 
    </div> 
    ... 
    alot of input here 
    ... 

</form> 

然後在輸入的處理中,再次使用上述功能:

<?php 

// This extract is not needed for the next loop, but you might need it still: 
extract($_POST, EXTR_PREFIX_ALL, 'input'); 

// go through all inputs that are required and test for empty 
// until you find one, and produce the appropriate response 
foreach($required as $name) { 
    if (empty($_POST[$name])) { 
     // main (error?) function here 
     break; // no need to continue the loop as we already found an empty one 
    } 
} 

?>