Reputation: 73
I'm having trouble with the variable $_SESSION['number']. The user can set it in the form, but it disappears after they hit Submit! two or more times with the field empty. How can I keep the $_SESSION['number'] after hitting Submit? Thanks
<form action=" <?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="number"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// starting the session
session_start();
$_SESSION['number']=0;
if (isset($_POST['Submit'])){
if($_POST['number'] != ''){
$_SESSION['number'] = $_POST['number'];
}
$_SESSION['number'] = $_SESSION['number'];
}
echo 'number='.$_SESSION['number'];
Upvotes: 1
Views: 643
Reputation: 73
Thanks Lakmal, I worked with your code and found that if I set the $_SESSION variable before the "if else loop" and keep the "if else" logic real simple, It works. The $_SESSION variables work very well for this type of code.
<?php
//starting the session
session_start();
$num = 0;
if(!isset($_SESSION['number'])) $_SESSION['number']=0;
if(isset($_POST['Submit'])){
if($_POST['number'] != ''){
$_SESSION['number'] = $_POST['number'];
}
echo 'number='.$_SESSION['number'];
}
?>
<form action=" <?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="number"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
Upvotes: 1
Reputation: 139
Your code should like this,
<?php
// starting the session
session_start();
$num = 0;
if (isset($_POST['Submit'])) {
if ($_POST['number'] == '') {
$_SESSION['number'] = $num;
} else {
$_SESSION['number'] = $_POST['number'];
}
echo 'number = '.$_SESSION['number'];
}
?>
<form action=" <?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="number"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
And think It will help you.
Upvotes: 1