開発環境
- OS X Lion - Apple(OS)
- Apache (Web Server)
- PHP (サーバーサイドプログラミング言語、スクリプト言語)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
『初めてのPHP5』 (David Sklar 著、 桑村 潤 翻訳、 廣川 類 翻訳、 オライリー・ジャパン、2005年、ISBN978-4-87311-257-2)の6章(Webフォームの作成)6.7(演習問題)3を解いてみる。
3.
HTML、PHPのソースコード(BBEdit)
<?php
function calc_add($a, $b){
return $a + $b;
}
function calc_sub($a, $b){
return $a - $b;
}
function calc_mul($a, $b){
return $a * $b;
}
function calc_div($a, $b){
return $a / $b;
}
if(array_key_exists('_submit_check', $_POST)) {
if($errors = validate_form()){
show_form1($errors);
print "?";
show_form2();
} else {
process_form();
}
} else {
show_form1();
print "?";
show_form2();
}
function show_form1($errors = ''){
if(array_key_exists('_submit_check', $_POST)){
$defaults = $_POST;
} else {
$defaults = array('lhs' => 5, 'rhs' => 10);
}
if($errors){
print 'エラー<ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print <<<_HTML_
<form method="POST" action="{$_SERVER['PHP_SELF']}" >
<input type="text" name="lhs" value="{$defaults['lhs']}"/>
<select name="operator">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">*</option>
<option value="div">/</option>
</select>
<input type="text" name="rhs" value="{$defaults['rhs']}"/>
=
_HTML_;
}
function show_form2(){
print <<<_HTML_
<input type="submit" value="calc" />
<input type="hidden" name="_submit_check" value="1" />
</form>
_HTML_;
}
function validate_form(){
$errors = array();
if($_POST['lhs'] != strval(floatval($_POST['lhs']))){
$errors[] = "左側に数値を入力してください";
}
if($_POST['rhs'] != strval(floatval($_POST['rhs']))){
$errors[] = "右側に数値を入力してください";
}
return $errors;
}
function process_form(){
show_form1();
switch($_POST['operator']){
case "add": print calc_add($_POST['lhs'], $_POST['rhs']); break;
case "sub": print calc_sub($_POST['lhs'], $_POST['rhs']); break;
case "mul": print calc_mul($_POST['lhs'], $_POST['rhs']); break;
case "div": print calc_div($_POST['lhs'], $_POST['rhs']); break;
default:print "?";
}
show_form2();
}
?>
0 コメント:
コメントを投稿