[英]adding html textbox value in php variable
I want to sum values in a php variable from html text box my php code is as under 我想对来自HTML文本框的PHP变量中的值求和,我的PHP代码如下
$total = 0;
$val2 = $_POST['val1'];
$total += val2;
echo "Sum of value is ". $total;
This is my HTML: 这是我的HTML:
<form action="add.php" method="post" >
<input type="text" name="val1" />
...
...
use Session
使用
Session
session_start();
$total = 0;
$val2 = $_POST['val1'];
$_SESSION["total"]+= $val2;
echo "Sum of value is ". $_SESSION["total"];
A session is a way to store information (in variables) to be used across multiple pages
会话是一种存储要在多个页面中使用的信息(以变量形式)的方式
Use sessions; 使用会话;
session_start();
$val2 = $_POST['val1'];
$total = 0;
if(isset($_SESSION['prev_sum'])){
$total = $_SESSION['prev_sum'] + $val2;
}else{
$total += $val2;
}
$_SESSION['prev_sum'] = $total;
echo "Sum of value is ". $total;
It should be something like 应该是这样的
session_start();
$val1 = isset($_SESSION['val2']) ? $_SESSION['val2'] : 0 ;
$val2 = $_POST['val2'];
$total = $val1 + $val2;
$_SESSION['val2'] = $total;
echo "Sum of value is ". $total;
AND 和
<form action="add.php" method="post" >
<input type="text" name="val1" value="<?php echo $_POST['val1'] ?>" />
<input type="text" name="val2" />
....
$total+=$val2
refers to $total = $total + $val2
so the values
are being summed up in the variable $total
instead of $val2
. $total+=$val2
指的是$total = $total + $val2
因此将values
累加到变量$total
而不是$val2
。 So replace $val2
in echo
statement with $total
. 因此,将
echo
语句中的$val2
替换$val2
$total
。
you have to use sessions or database(which is not suitable for your current problem) for this because http is stateless protocol ie it cannot maintain its state so as soon as new request originates all the variables set to its default values 您必须为此使用会话或数据库(这不适合您当前的问题),因为http是无状态协议,即它无法维持其状态,因此新请求一经发出,所有设置为默认值的变量都将立即发出。
session_start();
$sum= 0;
$val2 = $_POST['val1'];
$_SESSION["sum"]+= val2;
echo "Sum of value is ". $_SESSION["sum"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.