PHP表单多值字段
2018-02-22 16:40 更新
PHP教程 - PHP表单多值字段
表单字段可以发送多个值,而不是单个值。
实施例1
例如,以下表单字段能够向服务器发送多个值:
<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>
多选列表框,允许用户选择一个或多个(或不选)选项。
实施例2
<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"/>
复选框可以具有相同的名称(myTask),但具有不同的值(testTask和designTask)。
如果用户选中两个复选框,testTask和designTask,在myTask字段名称下发送到服务器。
怎么样
那么如何处理PHP脚本中的多值字段呢?诀窍是添加方括号([])在HTML表单中的字段名称后面。
当PHP引擎看到提交的表单字段名称在末尾使用方括号,它会在$ _GET或$ _POST中创建一个嵌套的值数组和$ _REQUEST超全局数组,而不是单个值。
然后,您可以拉出单个值嵌套数组。 因此,您可以创建一个多选列表控件,如下所示:
<select name="mySelection[]" id="mySelection" size="3" multiple="multiple"> ... </select>
然后,您可以检索包含提交的字段值的数组,如下所示:
$favoriteLanguage = $_GET["mySelection"]; // If using get method $favoriteLanguage = $_POST["mySelection"]; // If using post method
实施例3
具有多值字段的注册表
<!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>
现在将以下脚本作为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>
以上内容是否对您有帮助:
更多建议: