Created
October 21, 2016 14:22
-
-
Save twlca/55635f634134333e784baf528b9a3051 to your computer and use it in GitHub Desktop.
以 PHP 的陣列定義表單輸入項參數,再以迴圈完成每個輸入項名稱加上 $prefix,以保障資料庫安全
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$prefix = 'tdva_'; | |
$application_unit_info = array( | |
array( | |
'type' => 'text', | |
'name' => $prefix . '運用單位' | |
), | |
array( | |
'type' => 'text', | |
'name' => $prefix . '承辦人' | |
), | |
array( | |
'type' => 'text', | |
'name' => $prefix . '聯絡電話' | |
), | |
); | |
$trainee_fields = array( | |
array( | |
'type' => 'text', | |
'name' => $prefix . '學員姓名' | |
), | |
array( | |
'type' => 'text', | |
'name' => $prefix . '身分證字號' | |
), | |
array( | |
'type' => 'text', | |
'name' => $prefix . '出生年月日' | |
), | |
array( | |
'type' => 'text', | |
'name' => $prefix . '聯絡電話' | |
), | |
array( | |
'type' => 'text', | |
'name' => $prefix . '郵遞區號', | |
'pattern' => '^[1-9]{1}[0-9]{2}$' | |
), | |
array( | |
'type' => 'text', | |
'name' => $prefix . '地址', | |
'size' => 46 | |
), | |
array( | |
'type' => 'checkbox', | |
'name' => $prefix . '素食者請打勾' | |
), | |
); | |
?> | |
<?php | |
<?php | |
// TODO: | |
// 1. 在迴圈中加入 str_replace 函數是否有更佳方法? | |
// 2. 若不是在定義陣列時即加上 $prefix,是否在後台再加為宜 | |
// 3. 希望呈現在 browser debugger 中的是乾淨的 name,複雜的在後台再加是否合適? | |
$field_group = &$trainee_fields; | |
echo '<table>'; | |
for ( $i = 0; $i < count( $field_group ); $i++ ) { | |
echo '<tr><th><label for="' . str_replace( $prefix, '', $field_group[$i]['name'] ) . '">' . str_replace( $prefix, '', $field_group[$i]['name']) . '</label></th><td><input '; | |
foreach ( $field_group[$i] as $key=>$value ) { | |
$key = str_replace( $prefix, '', $key ); | |
$value = str_replace( $prefix, '', $value ); | |
echo $key . '="' . $value . '" '; | |
} | |
echo ' /></td></tr>'; | |
} | |
echo '</table>'; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
藉由設定 form field 的各種參數,例如 form element (input, textarea, select...) 以及 element 的 attributes 於 array 中,可以將「繪製 FORM 表單」的 HTML 輪入轉換成寫 array 參數,如此,在 WordPress 應用時繁瑣而極容易出錯又不易偵錯的語法隔離出來,且可以將程式段落寫成函式,並同時將一些 寫在函式中,避免出錯或忘記寫入。這樣的工作可以以如上的方式完成。
程式段落中包含最基本的 Nested Loop,僅僅將 Array 的參數寫入到 form 中。真正 implement 時,包含 nonce, 額外的 hidden fields,submit / reset 等。