1
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?

チェックボックスの値の送信について

Posted at

チェックボックスとPHP処理の基本

1. HTML側のチェックボックスフォーム

複数のチェックボックスに同じ name を付けることで、選択された値だけが送信されます。

<form action="/submit" method="post">
  <input type="checkbox" name="fruit" value="apple">Apple<br>
  <input type="checkbox" name="fruit" value="banana">Banana<br>
  <input type="checkbox" name="fruit" value="cherry">Cherry<br>
  <input type="submit">
</form>

2. チェックなしで送信された場合のPHP側の処理

1つもチェックされなかった場合、$_POST['fruit'] は「存在しない」ため、 isset()empty() での確認が必要です。

<?php
if (isset($_POST['fruit'])) {
    $selected = $_POST['fruit'];
    echo "選択された果物: " . htmlspecialchars($selected);
} else {
    echo "果物が選択されていません。";
}
?>

3. 複数選択を配列として受け取る方法

name="fruit[]" のように配列形式で送ると、複数選択に対応しやすくなります。

<form method="post">
  <input type="checkbox" name="fruit[]" value="apple">Apple<br>
  <input type="checkbox" name="fruit[]" value="banana">Banana<br>
  <input type="checkbox" name="fruit[]" value="cherry">Cherry<br>
  <input type="submit">
</form>
<?php
if (!empty($_POST['fruit'])) {
    foreach ($_POST['fruit'] as $fruit) {
        echo htmlspecialchars($fruit) . "<br>";
    }
} else {
    echo "果物が選択されていません。";
}
?>
1
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
1
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?