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\portal\rehabCreate.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.
Related
This code is supposed to save a random number into a session varible when generateCode is pressed
It does generate it and store in the variable but when i try to acces is from the if(isset($_POST['confirmCode'])){ it is empty
<?php
session_start();
if(isset($_POST['generateCode'])){
$_SESSION["key"] = mt_rand(100000, 999999);
}
if(isset($_POST['confirmCode'])){
die($_SESSION["key"]);
}
?>
<form method="POST">
<input type="text" name="confcode" placeholder="Confirmation Code">
<input type="submit" name="confirmCode" value="Confirm">
<input type="submit" name="generateCode" value="Generate">
</div>
</div>
</form>
Does anybody know how i can make a variable that stays some time even after post request
Edit:
So to get this clear confirmCode is a button to submit the code entered in a <input type="text></input> But i decided to not include the code to get the content if confCode because this question is about how to keep a variable generated by mt_rand even after <input type="submit"> is pressed
The problem isn't the button, PHP actually puts the name and value in the parameters.
The problem is with the die function. It expects either a message (string) or a status code (integer). When you generate the random number it interprets the message as a number (status code) instead of a string (message). To make sure it interprets the key as a string you could wrap it in a strval() function like this:
die(strval($_SESSION["key"]));
I am working on a PHP project - I had one form post a date to another form
I made some changes (although none to the input in question)
Now all other inputs are updated with their Posted values, except the date
If I manually set the date in HTML it works:
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="2009-01-01"></div>
If I set it to the following, it doesn't:
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="<?php echo (isset($DateCourse))?$DateCourse:'';?>"></div>
The below:
$DateCourse = ($_POST["DateCourse"]);
var_dump($_POST["DateCourse"]);
var_dump($DateCourse);
Returns:
string(10) "2019-01-05" - means the post value is set
Notice: Undefined variable: DateCourse in /home/bitecons/bts.biteconsulting.co.za/v2/editccr.php on line 119 - how can it be undefined, I just defined it
NULL
What on earth am I doing wrong? Apart from using PHP :P
Flow as requested:
Records.php:
This is the function to prepopulate my posted fields:
function Prefill(x) {
TabletoEdit = x.closest('table').id;
SelectedRow = x.rowIndex;
document.getElementById("EntryEditing").value = x.cells[19].innerHTML;
document.getElementById("DateCourse").value = x.cells[0].innerHTML;
document.forms["records"].submit();
}
Then I also have:
<form action="editrec" method="post" id="records">
<input type='hidden' name='Period' id='Period' />
<input type='hidden' name='Month' id='Month' />
<input type='hidden' name='res' id='res' />
<input type='hidden' name='CustName' id='CustName' />
<input type='hidden' name='DateCourse' id='DateCourse' />
</form>
The Prefill gets called, then submits the form
I have tracked and DateCourse has data, but when getting to the other form, it "disappears":
if(!empty($_POST)) {
$DateCourse = ($_POST["DateCourse"]);
$CustName = ($_POST["CustName"]);
}
For example, CustName is filled in, but not DateCourse?
Side question:
Would this return true if another post var is not set (unrelated to this one):
if(!empty($_POST))
I think You use wrong Code
you Must Submit First Form And Then Use $DateCourse this In another Form in POSTBACK
One of the best way is to define $DateCourse too like
<?php
$DateCourse = "";
if(!empty($_POST["DateCourse"])) {
$DateCourse = ($_POST["DateCourse"]);
}
?>
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="<?php echo $DateCourse;?>"></div>
Okay, apologies folks, but it may help others in the future.
I had a function call to an old function - this failed, causing my variable to never get defined... I knew it was something stupid, but sometimes one needs a sound board...
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I'm trying to study php and I'm already on the sessions part where I want to input something on my first page that would then be an output for the second page
1stpage.php
<?php session_start();?>
<form method="post">
Enter a number: <input type="number" name="num1" min="1" max="20" value="<?php echo $_SESSION["$num1"];?>">
<a href ="2ndpage.php">
<input type="button" name="select" value="select">
</a>
</form>
2ndpage.php
<?php
session_start();
echo $_SESSION[$num1];
?>
Well, it does'nt work and I'm getting lots of undefined index error. Any fix guys? Thanks in advance.
Take a look at form handling:
http://www.w3schools.com/php/php_forms.asp
If you still want to save the value into a session use:
$_SESSION['num1'] = $_POST['num1'];
1stpage.php
<?php session_start();?>
<?php if(isset($_SESSION['num1'])) $num1 = $_SESSION['num1']; else $num1 = ''; ?>
<form method="post" action="2ndpage.php">
Enter a number: <input type="number" name="num1" min="1" max="20" value="<?php echo $num1;?>">
<input type="submit" name="select" value="select">
</form>
2ndpage.php
<?php
session_start();
$_SESSION['num1'] = $_POST['num1'];
echo $_SESSION['num1'];
?>
What I have done here is I have first looked into the session if the num1 offset has been set into the session. If its not then I give $num as blank else I set the assign the value from session to $num.
Now when we input something and post it on 2nd page, the posted value is assigned to the variable in session and is displayed as well. So that next time you visit 1stpage.php while in same session, you will see your last posted value.
Let us know if it solves your practive problem or if this is not what you wanted.
I believe this is what you're trying to do:
Page 1:
<?php
session_start();
if(isset($_POST['select'])){
$num1 = $_POST['num1'];
$_SESSION['num1'] = $num1;
}
?>
<form method="post">
Enter a number: <input type="number" name="num1" min="1" max="20" value="<?php echo $_SESSION['num1']; ?>">
<input type="submit" name="select" value="select">
Click here to See the Value
</form>
Page 2:
<?php
session_start();
echo $_SESSION['num1'];
?>
Where, at first you press the select to enter the value inside
num1 then click on Click here to See the Value to see it.
I don't think you understand how all this works. You're having PHP output a session variable into a text box and expecting that that text box will somehow magically update your session. Somewhere you have to pass that data back to PHP and update it. So let's make your code into a process
<?php session_start(); ?>
<form method="post" action="process.php">
Enter a number: <input type="number" name="num1" min="1" max="20" value="<?php echo $_SESSION["$num1"];?>">
<input type="submit" name="select" value="select">
</form>
What I've done is make this form do a basic POST. If you want to avoid this you can use AJAX instead (same result using JS instead of HTML)
Next, let's make a basic process.php intermediate page
<?php
session_start();
$_SESSION['num1'] = (int)$_POST['num1'];
header('Location: 2ndpage.php');
Now we have a logistics chain for the data. You accept the data in your HTML and POST it to this page. It then takes it, sanitizes it (note I cast it to an (int) so we are certain this is a number) and then issues a redirect to the browser which takes you to your original landing page, which should now work.
This is all oversimplified for the process of teaching. You could have your form submit directly to 2ndpage.php and process there. Or, as I said before, you could use AJAX to send to process.php and when it returns some success parameter you then use JS to redirect. You have many options here.
Put this on the first page:
$_SESSION['num1'] = $num1;
and this on the second
$num1 = $_SESSION['num1'];
The code is working, however I still recieve undefined index with the Id "addmsg"
<?php
$addmsg=$_GET["addmsg"];
if (isset($addmsg)) // If the user wants to add a Message
{
?>
This is the code for the textarea and the submit buttons:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<p>Post your Message:<br />
<textarea name="msg" rows="10" cols="70" wrap></textarea><br />
<input type="submit" name="smtmsg" value="SUBMIT" /></p>
</form>
Lastly, this code is to connect to the Mysql database
$url = $_SERVER['PHP_SELF'] ."?addmsg=1";
You need to check isset before assigning the variable:
<?php
if (isset($_GET["addmsg"])) // If the user wants to add a Message
{
$addmsg=$_GET["addmsg"];
}
?>
You use $_POST so the field msg would never be evaluated here. Either change the $_GET['addmsg'] to $_POST['msg'] or change the field msg to addmsg and change the form type to "get"
There is no field named "addmsg" in your HTML. The only one you have is named "msg".
Your form is submitting to <?php echo $_SERVER['PHP_SELF'];?>, so on your server side, there is no index addmsg in the $_GET superglobal.
You should change your form action to <?php echo $_SERVER['PHP_SELF'] . "?addmsg=1";?> as you have in the last line of your question.
The message mean exactly what it says. The is nothing set at $_GET['addmsg'].
In this case, you have two problems. Your form method is set to post. You must therefore look for your value in $_POST
Second, you must actually have a field named addmsg in your form. The field in your form is named msg. So the value would be available as $_POST['msg']
There is 2 errors:
First:
IF the method is "post", the variable is $_POST.
Second:
The textarea's name is "msg", then you have to do $_POST["msg"].
Of course, if methos="get", the variable is $_GET["msg"]
I have been working on a Timesheet Management website. I have my home page as index.php
//index.php (only relevant portion shown)
<?php
session_start();
if($_SESSION['logged']=='set')
{
$x=$_SESSION['username'];
echo '<div align="right">';
echo 'Welcome ' .$x.'<br/>';
echo' <b><u>Logout</u></b>' ;
}
else if($_SESSION['logged']='unset')
{
echo'<form id="searchform" method="post" action="processing.php">
<div>
<div align="right">
Username <input type="text" name="username" id="s" size="15" value="" />
Password <input type="password" name="pass" id="s" size="15" value="" />
<input type="submit" name="submit" value="submit" />
</div>
<br />
</div>
</form> ';
}
?>
The problem I am facing is that during the first run of this script I get an error Notice: Undefined index: logged in C:\wamp\www\ps\index.php but after refreshing the page the error vanishes.
How can I correct this problem? logged is a variable which helps determine whether the user is logged in or not. When the user is logged in $_SESSION['logged'] is set, otherwise unset. I want the default value of $_SESSION['logged'] to be unset prior to the execution of the script. How can I solve this problem?
When the session is initially started, $_SESSION is an empty array and $_SESSION['logged'] does not exist. And read access to uninitialized variables or array indexes throw a notice (given that the error reporting level covers notices):
echo $undefinedVariable;
$emptyArray = array();
echo $emptyArray['undefined index'];
To tackle this you should test if the variable or array index you want to read actually exists. For variables there is isset and for array indices you can either use isset too or array_key_exists.
you can also prevent a function from throwing an error if you use the '#' symbol, e.g. #function_call();.
do you really want to do "if($_SESSION['logged']='unset')" ? if you want to make an assignment, consider taking out the "if" to make your code more legible. otherwise, you probably wanted to use the equality operator. :-)