我有一个简单的php计算器,代码是:
<html>
<head>
<title>PHP calculator</title>
</head>
<body bgcolor="orange">
<h1 align="center">This is PHP Calculator</h1>
<center>
<form method="post" action="phptest.php">
Type Value 1:<br><input type="text" name="value1"><br>
Type value 2:<br><input type="text" name="value2"><br>
Operator:<br><input type="text" name="sign"><br>
Result:<br><input type"text" name="result">
<div align="center">
<input type="submit" name="submit" value="Submit">
</div>
</form>
</center>
<?php
if(isset($_POST['submit'])){
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
if($value1=='') {
echo "<script>alert('Please Enter Value 1')</script>";
exit();
}
if($value2=='') {
echo "<script>alert('Please Enter Value 2')</script>";
exit();
}
if($sign=='+') {
echo "Your answer is: " , $value1+$value2;
exit();
}
if($sign=='-') {
echo "Your answer is: " , $value1-$value2;
exit();
}
if($sign=='*') {
echo "Your answer is: " , $value1*$value2;
exit();
}
if($sign=='/') {
echo "Your answer is: " , $value1/$value2;
exit();
}
}
?>
我想要做的就是答案应该显示在结果输入字段中,而不是单独回显它们。请帮忙?我知道它很简单,但我是PHP的新手。
答案 0 :(得分:9)
一种方法是将所有PHP代码移到HTML上方,将结果复制到变量中,然后将结果添加到<input>
标记中。
试试这个 -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
答案 1 :(得分:0)
在表格内,您可以使用此代码。替换您的变量名(我使用$ variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
答案 2 :(得分:0)
试试这个
<input class="qtytext-box" type="number" value= <?php echo $colll2; ?> >