0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP 配列で複数の値をpostする方法

Posted at

#formでpost時配列で値を渡す方法

例)
index.php



<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form action="eat.php" method="post" >
  <select name="lunch[]" id="" multiple>
  <option value="pork">buta</option>
  <option value="befe">ushi</option>
  <option value="dog">inu</option>
  <option value="chcken">tori</option>
  <option value="snake">hebi</option>
  </select>
  <input type="submit" name='subnit'>
  </form>
</body>
</html>

eat.php


<?php 
$a = $_POST['lunch'];
if(isset($_POST['lunch'])){
    foreach($_POST['lunch'] as $choice){
      print "you want $choice .<br/>";
    }
  }

結果
スクリーンショット 2021-03-08 10.52.06.png
3つの値をshiftで選択すると、、

スクリーンショット 2021-03-08 10.52.10.png

上記の表示がされる。

##ポイント
selectタグのname属性をname='lunch[]'[]にしている。
これが無くてname='lunch'では複数をshiftで選択してpostしても複数の値を$_POSTで取得できない。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?