我正在制作一个贷款计算器,我想运行一些使用POST方法从表单中发布的计算。运行代码时代码未执行。我在哪里想念它?
我已经运行了没有该函数的代码,并且看起来运行良好,但是当我将其放入一个函数中时,它却没有运行。
function loancal()
{
if(isset($_POST['submit'])) {
$principal = $_POST['principal'];
$intrstRate = $_POST['intrest'];
$tenure = $_POST['tenure'];
$result = ($principal * $intrstRate * $tenure) ;
echo $result;
} else {
echo '00.00';
}
}
这是在提交函数之后调用该函数的行:
<h1 class="title is-2"> $<?php loancal(); ?></h1>
我期望out从$ 00.00变为例如计算结果,但输出仍为$ 00.00
这是表格(节选)。
<form method="post" action="">
<input type="text" name="principal">
<input type="text" name="intrest">
<input type="date">
<input type="text" name="tenure">
<button type="submit">Calculate</button>
<button type="reset" >Clear</button>
</form>
答案 0 :(得分:2)
所以我的第一个答案是您的问题,您需要给您的“提交”按钮起一个名字。
<button name="submit" class="button is-rounded is-primary" type="submit">Calculate</button>
答案 1 :(得分:0)
这是使代码执行的一种方法:
<?php
function loancalc() {
$result = '0.00';
if( isset( $_POST['submit'] )){
// inspecting submitted values so that...
foreach ($_POST as $key => $value){
$bool[$key] = ctype_print( $value );
}
// ... if proven valid, then make assignments
if ( $bool['principal'] && $bool['interest'] && $bool['tenure'] ) {
// array destructuring available since PHP 7.1
[$principal, $interestRate,$tenure] =
[$_POST['principal'],
$_POST['interest'],
$_POST['tenure']];
$result = $principal * $interestRate * $tenure;
} // inner if
} // if POSTed
echo number_format( $result,2,'.',',' ); // default English representation
} // end func
?>
<html>
<head>
<title>Untitled</title>
<style>
#submit {
background: #000;
color: lime;
}
#clear {
background: #000;
color: cyan;
}
input {
background: #ffffee;
color: #303;
}
h1 {
font-size: 32pt;
margin-bottom: 3em;
color: #f0c;
}
</style>
</head>
<body>
<h1>$
<?php loancal(); ?>
</h1>
<form method="post" action="">
<input type="text" name="principal" id="principal">
<input type="text" name="intrest" id="intrest">
<input type="date">
<input type="text" name="tenure" id="principal">
<button type="submit" name="submit" id="submit">Calculate</button>
<button type="reset" id="clear">Clear</button>
</form>
</body>
</html>
只有具有name
属性的表单值才可以正确提交。 Id
属性是可选的,对于前端代码操作非常方便。
要点:请务必将用户提交的数据视为可疑内容,即可能被污染。在此示例中,简单的检查可确保用户输入值仅包含可打印字符。
(PHP代码here的相关演示。)
精制:
number_format()
对数字进行格式化,以使数字更易于使用。