開発環境
- OS X Lion - Apple(OS)
- Apache (Web Server)
- PHP (サーバーサイドプログラミング言語)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
『初めてのPHP5』 (David Sklar 著、 桑村 潤 翻訳、 廣川 類 翻訳、 オライリー・ジャパン、2005年、ISBN978-4-87311-257-2)の6章(Webフォームの作成)6.7(演習問題)3を解いてみる。
3.
HTML、PHPのコード(TextWrangler)
<?php $operators = array("和", "差", "積", "商"); if($_POST['_submit_check']){ if($form_errors = validate_form()){ show_form($form_errors); } else { process_form(); } } else { show_form(); } function show_form($errors = ''){ if($errors){ foreach($errors as $key => $error){ print "$error<br />"; } } print <<<_HTML_ <form method="POST" action="$_SERVER[PHP_SELF]"> <label>a = <input type="text" name="lhs" /></label><br /> <label>b = <input type="text" name="rhs" /></label><br /> 演算: <select name="operator"> <option>和</option> <option>差</option> <option>積</option> <option>商</option> </select> <input type="submit" name="submit" value="計算" /> <input type="hidden" name="_submit_check" value="1" /> </form> _HTML_; } function validate_form(){ $errors = array(); $lhs = $_POST['lhs']; if(! strlen($lhs)){ $errors[] = "aの値を入力してください"; } elseif (strval(floatval($lhs)) != $lhs){ $errors[] = "aには数値を入力してください"; } $rhs = $_POST['rhs']; if(! strlen($rhs)){ $errors[] = "bの値を入力してください"; } elseif(strval(floatval($rhs)) != $rhs){ $errors[] = "bには数値を入力してください"; } return $errors; } function process_form(){ $rhs = floatval($_POST['rhs']); $lhs = floatval($_POST['lhs']); $result; switch($_POST['operator']){ case "和": $result = "$lhs + $rhs = " . ($lhs + $rhs);break; case "差": $result = "$lhs - $rhs = " . ($lhs - $rhs);break; case "積": $result = "$lhs * $rhs = " . ($lhs * $rhs);break; case "商": $result = "$lhs / $rhs = " . ($lhs / $rhs);break; } $result .= "<br /><a href='./sample54.php'>戻る</a>"; print $result; } ?>
HTMLソース
<form method="POST" action="/~kamimura/kamimura_blog/learning_php/sample54.php"> <label>a = <input type="text" name="lhs" /></label><br /> <label>b = <input type="text" name="rhs" /></label><br /> 演算: <select name="operator"> <option>和</option> <option>差</option> <option>積</option> <option>商</option> </select> <input type="submit" name="submit" value="計算" /> <input type="hidden" name="_submit_check" value="1" /> </form>
0 コメント:
コメントを投稿