LoginSignup
0
0

More than 5 years have passed since last update.

【PHP】 GETを使った受け渡しの備忘録02

Last updated at Posted at 2018-09-01

https://goo.gl/1ACSYG
の続きです。

送信先のtahnks.phpで送られたパラメータ消して表示すると下記画像のようにエラーになってしまう。

error.png

原因としては、index.html入力値である、nameとnenreiがthanks.phpに送られていないので、エラーとなってしまう。
下記コードで対策する

thanks.php
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>thanks.html</title>
</head>
<body>
    <?php ini_set('display_errors', 1); ?>

    <h1>thanks.php</h1>
    <p>お名前:
        <?php 
            // 入力値nameが存在すれば表示
            if (isset($_GET['name'])) {
                echo $_GET['name'];
            // なければ名前がないよ
            } else {
                echo '名前がないよ';
            };
        ?>
    </p>
    <p>年齢:
        <?php 
            if (isset($_GET['nenrei'])) {
            // 入力値nenreiが存在すれば表示
                echo $_GET['nenrei'];
            } else {
            // なければ年齢がないよ
                echo '年齢がないよ';
            }
        ?>
    </p>
</body>
</html>

これで下記のように入力値が存在していないthanks.phpアクセスしてもエラーがでなくなりました。

3.png

thanks.phpのコードを綺麗にする

html内でphpを混在させると今は単純なコードだから大丈夫らしいんですが、後々ブラックボックス化してくるとのことで。お掃除したコードが下記です。

タグの上で条件分岐を前もって記載しておき、$nameと$nenreiという変数に格納しておき、html内では変数をechoで呼び出します。

これで先ほどと結果は変わらず表示されます。

tahnks.php
<?php
    if (isset($_GET['name'])) {
        $name = $_GET['name'];
    } else {
        $name = '名前がないよ';
    }
    if (isset($_GET['nenrei'])) {
        $nenrei = $_GET['nenrei'];
    } else {
        $nenrei = '年齢がないよ';
    }
?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>thanks.html</title>
</head>
<body>
    <?php ini_set('display_errors', 1); ?>

    <h1>thanks.php</h1>
    <p>お名前:<?php echo $name ?></p>
    <p>年齢:<?php echo $nenrei; ?></p>
</body>
</html>

参考文献

WEBデザイナー・HTMLコーダーのための実践PHP入門 (1) メールフォームを自作する
https://www.udemy.com/phpbasics01/

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