Reputation: 389
This is a simplified version of the code I currently have:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="form" action="" method="post">
<input name="button1" type="submit" value="Submit">
</form>
<hr>
</body>
</html>
<?php
if (isset($_POST['button1'])){
echo 'Test';
}
?>
and this code outputs Test
when I click the button once, but when I click it another time, it clears the first echo, and reprints it, so the output will still be one Test
. Is there any way in PHP to stop it from clearing the first echo so the output would become TestTest
?
Upvotes: 1
Views: 68
Reputation: 2595
you could set a session variable
<?php
session_start();
if (isset($_POST['button1'])){
if(isset($_SESSION['myvar'])){
$_SESSION['myvar'] .= 'Test';
}else {
$_SESSION['myvar'] = 'Test';
}
echo $_SESSION['myvar'];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="form" action="" method="post">
<input name="button1" type="submit" value="Submit">
</form>
<hr>
</body>
</html>
I have not tested this code but it should work
NOTE: you may to trap potential errors if your session is not started this may answer your original question, however there may be better solutions depending what your end goal is.
make sure to include the above php code above the html markup EDITED: incorporated Fred sugestions
Upvotes: 2
Reputation: 40663
The web is stateless. Each time you click submit you start a new request which (as far as the server is concerned) is coming from a brand new user. The web server can't remember (or doesn't care) that you just made a request earlier. The act of clicking on the submit button creates a new request and loads the page from scratch.
PHP has a way around this by using sessions to maintain state information. A session is PHPs way of saying "hey I know who this person is, I've seen them before".
You can use the session to do this in the following way.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="form" action="" method="post">
<input name="button1" type="submit" value="Submit">
</form>
<hr>
</body>
</html>
<?php
if (isset($_POST['button1'])){
$_SESSION["counter"] = (isset($_SESSION["counter"])?$_SESSION["counter"]:0) + 1;
for ($i = 0;$i < $_SESSION["counter"];$i++)
echo 'Test';
}
?>
Upvotes: 3