简体   繁体   English

如何增加会话变量以进行提交

[英]How to increment session variable on for submit

I have form to add employess to database. 我有表格将员工添加到数据库。 I have to count how many employess were added during one session and display it somewhere on the screen. 我必须计算在一次会话中增加了多少名雇员,并将其显示在屏幕上的某处。

Right now my form_validation.php looks like this: 现在我的form_validation.php看起来像这样:

<?php
 session_start();

 if(formValidationIsCorrect){
   $_SESSION['counter']++;
   header("location:pageWithFormDetails.php);
 }

in pageWithFormDetails.php I have to display employee information from form (name, age, etc.), and how many employess were added during this session. pageWithFormDetails.php我必须显示表单中的员工信息(姓名,年龄等),以及在此会话中添加了多少名雇员。

My problem is, that when on pageWithFormDetails.php I do 我的问题是,当在pageWithFormDetails.php上时

<?php echo $_SESSION['counter']; ?> <?php echo $_SESSION['counter']; ?> it always displays 1 , even If i refill form few times. <?php echo $_SESSION['counter']; ?>它始终显示1 ,即使我几次填写表格也是如此。 I guess everytime I complete form, my counter variable is reset, and then incremented by 1 . 我猜每次我填写表格时,我的counter变量都会重置,然后加1 Is there a way not to reset this variable every time I complete form, and validate it? 有没有办法在我每次填写表格并进行验证时都不重置此变量?

You need to use database input and then output. 您需要先使用数据库输入,然后再使用输出。 When you are attempting to $_SESSION ++. 当您尝试使用$ _SESSION ++时。 There you can use ++ in db variable then -1 when you are destroying the session. 在那里,可以在db变量中使用++,然后在销毁会话时使用-1。 That's how I did this when I needed similar type of thing. 当我需要类似类型的东西时,我就是这样做的。

You can try this code snippet and change your code accordingly 您可以尝试使用此代码段并相应地更改代码

<?php
session_start();
if(isset($_POST['submit'])){
  array_key_exists('counter', $_SESSION) ? $_SESSION['counter']++ : ($_SESSION['counter'] =1);
  echo $_SESSION['counter'];
}
?>
<form action="" method="post">
    <input type="submit" name="submit" value="submit" />
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM