1
2

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 5 years have passed since last update.

phpで簡易電卓を作る②

Posted at

phpで簡易電卓を作る

前回記事はこちら→https://qiita.com/pezio/items/ba31b0cba33b54c25a82

課題

・数値入力欄に数値以外を入力されたらどうする?
・続けて計算ができない

エラーハンドリング

caluculate.php
<?php
$number1 = $_POST['number1'];
$symbol = $_POST['symbol'];
$number2 = $_POST['number2'];
$answer ='';
if (isset($number1) && isset($number2) && is_numeric($number1) && is_numeric($number2)) {
    switch ($symbol) {
         case '+':
             $answer = $number1 + $number2;
             break;
         case '-':
             $answer = $number1 - $number2;
             break;
         case '*':
             $answer = $number1 * $number2;
             break;
         case '/':
             $answer = $number1 / $number2;
             break;
    };
    header('Location: index.php/?answer='.$answer);
} else {
    $message = '無効な値です';
    header('Location: index.php/?message='.$message);
};

ifの中で、(①要素が空白じゃない②数字である)場合のみswitch文への処理を行う。

is_numeric — 変数が数字または数値形式の文字列であるかを調べる
isset — 変数が宣言されていること、そして NULL とは異なることを検査する

条件が満たされない場合は変数$messageにメッセージをつめて、パラメーターを送る。
それ以外の場合は計算結果を$answerにつめて送る。

 index.php

index.php
<!DOCTYPE html>
<html lang='ja'>
  <head>
    <meta charset="utf-8">
    <title>Caluculator</title>
  </head>
  <body>
    <h1>電卓(簡易版)</h1>
    <form class="formula" action="calculate.php" method="post">
      数字1:<input type="string" name="number1"><br>
      記号:<select name="symbol">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">×</option>
        <option value="/">÷</option>
      </select><br>
      数字2:<input type="string" name="number2" value=""><br>
      <input type="submit">
    </form>
    <h2>答え:<?php echo $_GET['answer']?></h2>
    <h2><?php echo $_GET['message']?></h2>
    <a href="/"><input type="submit" value="リセット" ></a>
  </body>
</html>

$messageを表示するために<h2><?php echo $_GET['message']?></h2>で表示。
<a href="/"><input type="submit" value="リセット" ></a>でトップへのリンクを作ることで、計算結果のリセットが可能に。

次回

機能追加
 ・数字入力欄を新たに追加できるようにする

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?