表單字段可以發(fā)送多個值,而不是單個值。
例如,以下表單字段能夠向服務(wù)器發(fā)送多個值:
<label for="mySelection">What are your favorite widgets?</label> <select name="mySelection" id="mySelection" size="3" multiple="multiple"> <option value="PHP">PHP Language</option> <option value="Java">Java Language</option> <option value="CSS">CSS Language</option> </select>
多選列表框,允許用戶選擇一個或多個(或不選)選項。
<label for="tested">Have you tested?</label> <input type="checkbox" name="myTask" id="tested" value="testTask"/> <label for="designed">Have you designed?</label> <input type="checkbox" name="myTask" id="designed" value="designTask"/>
復(fù)選框可以具有相同的名稱(myTask),但具有不同的值(testTask和designTask)。
如果用戶選中兩個復(fù)選框,testTask和designTask,在myTask字段名稱下發(fā)送到服務(wù)器。
那么如何處理PHP腳本中的多值字段呢?訣竅是添加方括號([])在HTML表單中的字段名稱后面。
當PHP引擎看到提交的表單字段名稱在末尾使用方括號,它會在$ _GET或$ _POST中創(chuàng)建一個嵌套的值數(shù)組和$ _REQUEST超全局數(shù)組,而不是單個值。
然后,您可以拉出單個值嵌套數(shù)組。 因此,您可以創(chuàng)建一個多選列表控件,如下所示:
<select name="mySelection[]" id="mySelection" size="3" multiple="multiple"> ... </select>
然后,您可以檢索包含提交的字段值的數(shù)組,如下所示:
$favoriteLanguage = $_GET["mySelection"]; // If using get method $favoriteLanguage = $_POST["mySelection"]; // If using post method
具有多值字段的注冊表
<!DOCTYPE html5> <html> <body> <form action="index.php" method="post"> <label for="firstName">First name</label> <input type="text" name="firstName" id="firstName" value="" /> <label for="mySelection">What are your favorite widgets?</label> <select name="mySelection[]" id="mySelection" size="3" multiple="multiple"> <option value="PHP">PHP Language</option> <option value="Java">Java Language</option> <option value="CSS">CSS Language</option> </select> <label for="tested">Choice One?</label> <input type="checkbox" name="chioces[]" id="ChoiceOne" value="testTask" /> <label for="designed">Choice Two?</label> <input type="checkbox" name="chioces[]" id="ChoiceTwo" value="designTask" /> <input type="submit" name="submitButton" id="submitButton" value="Send Details" /> <input type="reset" name="resetButton" id="resetButton" value="Reset Form"/> </div> </form> </body> </html>
現(xiàn)在將以下腳本作為index.php保存在文檔根文件夾中:
<!DOCTYPE html5> <html> <body> <?php $mySelection = ""; $chiocess = ""; if ( isset( $_POST["mySelection"] ) ) { foreach ( $_POST["mySelection"] as $widget ) { $mySelection .= $widget . ", "; } } if ( isset( $_POST["chioces"] ) ) { foreach ( $_POST["chioces"] as $chioces ) { $chiocess .= $chioces . ", "; } } $mySelection = preg_replace( "/, $/", "", $mySelection ); $chiocess = preg_replace( "/, $/", "", $chiocess ); ?><dl> <dt>First name</dt><dd><?php echo $_POST["firstName"]?></dd> <dt>Favorite widgets</dt><dd><?php echo $mySelection?></dd> <dt>You want to receive the following chiocess:</dt><dd> <?php echo $chiocess?></dd> <dt>Comments</dt><dd><?php echo $_POST["comments"]?></dd> </dl> </body> </html>
更多建議: