I have two pages that i like to exchange variable. in the first page i have form like this:
<form method='post' action='rehabCreate2.php' onsubmit='return validateForm();'>
<input class="textbox" type='text' id='txt_stuNum' name='txt_stuNum'/ required>
<input type="submit" value="NEXT" id="btnNext">
</form>
then i set the session variable like this:
if ( isset( $_POST['btnNext'])){
$stuId=$_POST['txt_stuNum'];
$_SESSION["stuId"]=$stuId;
}
then in my page2 i want to it:
<?php
session_start();
$stuId=$_SESSION["stuId"];
echo $stuId;
?>
but it gives me error:
Notice: Undefined index: stuId in...
what am i missing? and another thing, how can i make a "back button" and the values are still in there?
EDIT: originally my "session_start()" was place at the top of the page1, but when i transfer it below my "" this error message show: Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\cerecare\portal\somepage.php:176) in C:\xampp\htdocs\cerecare\portalehabCreate.php on line 16
by the way: the line 176 of somepage is the end of the script tag and nothing else follows
First replace (give a name attr to submit button to get on POST)
<input class="textbox" type='text' id='txt_stuNum' name='txt_stuNum'/ required>
<input type="submit" value="NEXT" id="btnNext">
to
<input class="textbox" type='text' id='txt_stuNum' name='txt_stuNum' required />
<input type="submit" value="NEXT" id="btnNext" name="btnNext">
Add a session_start()
on page1
session_start();
if (isset( $_POST['btnNext'])){
$stuId=$_POST['txt_stuNum'];
$_SESSION["stuId"] = $stuId;
}
Then Add a check for session value exist or not on page2
$stuId=(isset($_SESSION["stuId"]) ? $_SESSION["stuId"] :'');
You forgot to add name for submit button but in addition whenever you are using any variable whether session or local variable just make sure it exists or not. so to save yourself from this problem always use this style of code given by @Rakesh Sharma.
$var = isset($_SESSION['any_var']) ? $_SESSION['any_var'] : '';
or the better way to perform check and reduce calculation mistake use like this
$var = ( isset($_SESSION['any_var']) && !empty($_SESSION['any_var']) ? $_SESSION['any_var'] : '';
In statements also always use this style
if ( isset($_SESSION['any_var']) && !empty($_SESSION['any_var'])){
/// code in statement
}
use this style of code always in your code and fee free at least from undefined index error and some calculation mistakes if value is empty.