1
1

More than 3 years have passed since last update.

HTMLのformで値を渡す

Last updated at Posted at 2020-06-16

HTMLのformで値を渡す

PHPでHTMLのformタグを使って値を渡す方法。
入力側で入れた数値をもとに三角形の面積を出す簡単なプログラムを作り、
それをもとに備忘録とします。
可読性を上げるためヘッダーとフッターは分割して部分テンプレート化し、
require文で呼び出してます。

まず入力側。

container_input.php
<?php require './header.php'?>
<form action="container_output.php" method="post">

  底辺<br>
  <input type="text" name="bottom"></br>
  高さ<br>
  <input type="text" name="height"></br>
  <input type="submit" value="投稿">

</form>
<?php require './footer.php'?>

入力した底辺と高さの値を、Webサーバを介して出力側のcontainer_output.phpに
リクエストパラメータとして渡す。

container_output.php
<?php require './header.php'?>
<?php

function calc($bottom,$height){

  //if文と正規表現で判定、底辺高さ共に値が数字ならtrue
  if(preg_match('/[0-9]/',$bottom) && preg_match('/[0-9]/',$height)){
    $result = ($bottom * $height) / 2 .'<a href="container_input.php">戻る</a>';
    return $result;
  } else {
    return '半角数値以外入力できません。'.'<a href="container_input.php">戻る</a>';
  }

} 

//送られてきた値をmb_convert_kana()の第二引数をnにして強制的に半角数字にする。
$bottom = mb_convert_kana($_REQUEST['bottom'],'n');
$height = mb_convert_kana($_REQUEST['height'],'n');

echo calc($bottom,$height);

?>
<?php require './footer.php'?>

PHPで定義されたスーパーグローバル変数の$_REQUEST['添字']で、リクエストパラメータを取得。
今回は入力側でinputタグのname属性に入れた文字列が添字部分に該当し、
これがキーとなり、値を呼び出す。

1
1
2

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
1