首页 > 技术文章 > 关于PHP的表单数组提交显示

cute-puli 2019-07-01 11:49 原文

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title></title>
 5     <meta charset="utf-8">
 6 </head>
 7 <body>
 8     <form action="" method="get">
 9         <select multiple="multiple" name="city[]">
10             <option value="">请选择城市</option>
11             <option value="北京">北京</option>
12             <option value="上海">上海</option>
13             <option value="广州">广州</option>
14             <option value="深圳">深圳</option>
15             <option value="大连">大连</option>
16         </select>
17         <input type="submit" value="点击">
18      </form>
19      <?php
20        header("Content-Type:text/html;charset=utf-8");
21 
22        $selected=isset($_GET["city"])?$_GET["city"]:"";
23        if(is_array($selected)){
24          foreach($selected as $key =>$value){
25          echo "city is".$value."<br>";
26       }
27     }
28     ?>
解释这里的
<select multiple="multiple" name="city[]"> ,属性被设置为multiple,意为可多选,
name的值被修改成了数组。
将city为名传递给selected变量,由于selected变量现在为数组,因此需要使用foreach遍历数组将value的结果全部打印出来。
29 
30 </body>
31 </html>

 

显示结果:

 

 


 

 

改变选择模式,使用圆形符号作为选框:

 

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title></title>
 5     <meta charset="utf-8">
 6 </head>
 7 <body>
 8       <form action="#" method="post">
 9           <input type="radio" name="test1" value="test1">
10           test1
11           <input type="radio" name="test1" value="test2">
12           test2
13           <input type="radio" name="test1" value="test3">
14           test3
15           <input type="submit" name="提交">
16       </form>
17 
18       <?php
19         $a=isset($_POST['test1'])?$_POST['test1']:'';
20         if($a){
21             echo $a;
22         }else{
23             echo "you not choose";
24         }
25       ?>
26 
27 </body>
28 </html>

 

 

显示结果:

 

当选择时:

 


 

 

对于表单多选时:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title></title>
 5     <meta charset="utf-8">
 6 </head>
 7 <body>
 8     <form action="#" method="post">
 9      <input type="checkbox" name="ch[]" value="test1">
10      test1
11      <input type="checkbox" name="ch[]" value="test2">
12      test2
13      <input type="checkbox" name="ch[]" value="test3">
14      test3
15      <input type="checkbox" name="ch[]" value="test4">
16      test4
17      <input type="submit" value="提交">
18      </form>

//
 注意:多选框的type为:checkbox,name需要标记为数组的类型,一定要写value,并且value的内容不相同
19      <?php
20       $a=isset($_POST['ch'])?$_POST[ch]:'';
21       if(is_array($a)){
22           foreach ($a as $key => $value) {
23               echo $value."<br>";
24           }
25       }else{
26           echo "you not choose";
27       }
28      ?>
29 </body>
30 </html>

 

显示结果:

 

推荐阅读