I've been searching for this solution for a while now and found some thread that were made previously regarding my same problem. But I still could not solve my problem. It's been days now and I still can't keep the array data from my HTML form to be stored in session. It just get overwritten every single time. Is there something wrong my my coding?
This is my PHP file that processes the input
<?php
if(!isset($_SESSION)){
session_start();
}
$student1 = array(
array(
'Name'=>$_POST['name'],
'Matric-No'=>$_POST['matric'],
'Gender'=>$_POST['gender'],
'Day'=>$_POST['DOBDay'],
'Month'=>$_POST['DOBMonth'],
'Year'=>$_POST['DOBYear'],
'Citizen'=>$_POST['citizen'],
'Marital'=>$_POST['kahwin'],
'Religion'=>$_POST['religion'],
'Active'=>$_POST['active'],
'Year-of-Study'=>$_POST['Cyear'],
'ID-Number'=>$_POST['idno'],
'Email'=>$_POST['email']
)
);
$_SESSION['data'] = $student1;
print_r($_SESSION);
?>
*Edit: So sorry... I forgot to mention that I do have a javascript validator to see if the user has successfully entered every form before submitting. And my problem is that when I refresh or go back to the form site, the previous data will not be there and if there is any new data that is entered. The previous data will be overwritten
You must set the $_SESSION['data'] only if a form has been submitted. Here is an example testing if name and religion has been sent (You could test for all variables to be sure):
session_start();
if ( isset( $_POST['name'] && isset( $_POST['religion'] ) {
$student1=array(
'Name'=>$_POST['name'],
'Matric-No'=>$_POST['matric'],
'Gender'=>$_POST['gender'],
'Day'=>$_POST['DOBDay'],
'Month'=>$_POST['DOBMonth'],
'Year'=>$_POST['DOBYear'],
'Citizen'=>$_POST['citizen'],
'Marital'=>$_POST['kahwin'],
'Religion'=>$_POST['religion'],
'Active'=>$_POST['active'],
'Year-of-Study'=>$_POST['Cyear'],
'ID-Number'=>$_POST['idno'],
'Email'=>$_POST['email']
);
$_SESSION['data']=$student1;
}
print_r($_SESSION);
?>
Now the $_SESSION['data'] is only changed when you POST a form with name and religion!
EDIT:
If you want to add more than one student in the session, try something like this:
$_SESSION['data'][]=$student1;
or simply:
$_SESSION['data'][]=$_POST;
To retrieve the data you do something like this:
foreach ( $_SESSION['data'] as $data )
echo 'Name: ' . $data['Name'];
or
for( $i = 0; $i < count( $_SESSION['data'] ); $i++ )
echo 'Name: ' . $_SESSION['data'][$i]['Name'];
Edit 2 Removed extra array from $student1 variable
You are missing session_start() to start session itself.
And make queries such $_SESSION['data'] = [your_array]; and test as isset($_SESSION['data'])
Check this page http://php.net/manual/en/ref.session.php
Related
Why am I loosing all the form data whenever I refresh the page? I am posting data from previous page and using echo $_POST['test']; it displays everything once and when I refresh the page, nothing gets printed.
I also tried using sessions but sessions are also being overwritten while refreshing the page.
<?php
SESSION_START();
$_SESSION['coupons_count'] = $_POST['points'];
$_SESSION['dateofcoupon'] = $_POST['dateofcoupon'];
$_SESSION['timeofcoupon'] = $_POST['timeofcoupon'];
$_SESSION['points'] = $_POST['points'];
$_SESSION['storename'] = $_POST['storename'];
?>
<h2>Coupon Details</h2>
<form id="form1" method="post">
<span style="width:120px;"><strong>Restaurant:</strong></span> <?php echo $_SESSION['storename']; ?>
<strong>Date:</strong> <?php echo $_SESSION['dateofcoupon']; ?>
<strong>Start Time:</strong> <?php echo substr($_SESSION['timeofcoupon'], 0, -10); ?>
<strong>End Time:</strong> <?php echo substr($_SESSION['timeofcoupon'], 8, -2); ?>
<strong>Coupons:</strong> </php echo $_SESSION['points']; ?>
Your scenario:
1) Add empty values from $_POST (No error? Since there is indexes defined yet)
2) You send form data
3) Save $_POST variables back to session
4) Refresh of page / removes all $_POST variables
5) You assign again empty variables
So basically you have to check $_POST variables existence and only save than:
if (isset($_POST['points'])) {
$_SESSION['coupons_count'] = $_POST['points'];
}
// repeat for all variables
That's the right behavior for a web form. You have a form, you are filling in the values and posting it to itself, then if you will refresh the page, as you are NOT posting any values again so you get noting displayed.
If you want to keep the values persistent across multiple refreshes, then post the form to a separate page [easiest solution];
Like you can make a page formdata.php and post it to formaction.php.
add action tag in your form with action="formaction.php"
and then refresh the action page multiple times and you will see all variables persistent.
Finally, I ended up using in a weird manner.
if($_POST['points'] != null)
{
$_SESSION['coupons_count'] = $_POST['points'];
$_SESSION['dateofcoupon'] = $_POST['dateofcoupon'];
$_SESSION['timeofcoupon'] = $_POST['timeofcoupon'];
$_SESSION['points'] = $_POST['points'];
$_SESSION['storename'] = $_POST['storename'];
}
I know, this is not a professional way but I am looking for a quick tip to get rid of this issue.
I'm not sure what you are complaining about. If you don't POST the values again when you refresh your page (and your browser should ask you whether it should send the form again), you can't expect the $_POST to have any values in it.
Anyway, this might help you a bit:
$pairs = array(
"coupons_count" => "points",
"dateofcoupon" => "dateofcoupon",
"timeofcoupon" => "timeofcoupon",
"points" => "points",
"storename" => "storename",
);
foreach ($pairs as $sessionVar => $postVar) {
if (isset($_POST[$postVar])) $_SESSION[$sessionVar] = $_POST[$postVar];
}
Where the session variables will be overwritten ONLY IF there are corresponding $_POST values defined.
I have very little experience with cookies so I don't know how to do that.
I have a t-shirt shop where each t-shirt has an $articleID.
Each time an user visits a t-shirt page, I would like to add the $articleID to a cookie.
Then add it to an array or something so I can retrieve it later.
There shouldn't be any duplicate $articleID even if the visitor visited the same $articleID twice.
Then on the main page, I want to retrieve the list of the last 5 $articleID visited and display a list of the ID.
How could I do that?
Thanks!
in order to store an array in your cookies you will need to serialize it so check if this code will help
$articles = array();
if ( isset($_COOKIE["viewed_articles"]) )
$articles = unserialize($_COOKIE["viewed_articles"]);
if ( ! in_array($articleID, $articles)){
$articles[] = $articleID;
}
// at the end update the cookies
setcookie("viewed_articles", serialize($articles));
I hope this helps and have a loop at this link
Something like this?
<?php
$article_id = 1; // Whichever article you're currently viewing
session_start();
if ( ! isset($_SESSION['viewed_articles']))
{
$_SESSION['viewed_articles'] = array();
}
if ( ! in_array($article_id, $_SESSION['viewed_articles']))
{
$_SESSION['viewed_articles'][] = $article_id;
}
Have you tried using Sessions? Cookies will store the values on the users computer. That data is transferred to your web server on every page load.
Sessions store data on the server side. Sessions work by storing a session ID as a cookie on the user's browser which corresponds to a session stored on the server.
If you are using PHP, you can initiate a session by using
<?php
session_start();
$_SESSION['key'] = 'value';
echo $_SESSION['key']; // outputs: value
?>
I'm trying to pass an error message from a server side form validator in a function back to the form it was submitted in. The validator is working as it prevents the rest of the code saving it to a database as planned. However I cant get it to pass back to the form to display the error
function saveComment(){
$validate = array();
$id = isset($_POST["articleId"]) ? $_POST["articleId"] : '';
if ( isset( $_POST['saveChanges'] ) ) {
if ( $_POST['name'] == "" ){
$validate['errorMessage'] = "Please fill out your name.";
header( "Location:".HOME_PATH."/.?action=viewArticle&articleId=".$_POST['articleID']."");
}
I' trying to pass it back to this
if ( isset( $validate['errorMessage'] ) ) {
echo $validate['errorMessage'];
}
When I remove the if on the display function I get the error unidentified index
What do I need to do to get the form to display the error message. Do I need to pass the array to the function that handles the display of the article?
FEEDBACK
For anyone that may find this useful I used #OliverBS post method pretty much unaltered.
Also thank you to #lethal-guitar as he explanation has helped me understand where I went wrong and the various methods that can be used to solve this problem +1
You're setting a variable $validate for your currently executing script. Afterwards, you send a redirect header. This will cause your browser to issue a new request, thus ending the currently executing script and scrapping the variable. The new request will trigger another script invocation, where the variable is not known anymore since it only existed for the duration of the first request.
HTTP is stateless, so every variable you set on the server side will only exist until you finish your current request and respond to the client. What you need is a way to pass this variable to the script handling the second request. There are several ways to do so:
Pass a GET parameter. You could append something like "&validationError=" . $validate['errorMessage'] to the URL you're passing to the Location header, and then in the display page access it via $_GET.
Save the validation status in the $_SESSION. The PHP manual contains a lot of information about sessions (maybe you're already using them?)
Restructure your code in a way that you don't redirect on error, but on success.
Some more information on the 3rd proposal: You write one PHP-Script which displays the form and handles the form post request. If validation fails, you simply redisplay, and insert the echo statement you already have. If it suceeds, you redirect to some success page. This way, the variable will remain accessible, since it's still the same request.
On a quick glance try this
Session way
Make sure to start the session by doing session_start(); at the top of the file where saveComment is and the isset checked.
function saveComment(){
$id = isset($_POST["articleId"]) ? $_POST["articleId"] : '';
if ( isset( $_POST['saveChanges'] ) ) {
if ( $_POST['name'] == "" ){
$_SESSION['errorMessage'] = "Please fill out your name.";
header( "Location:".HOME_PATH."/.?action=viewArticle&articleId=".$_POST['articleID']."");
}
if ( isset( $_SESSION['errorMessage'] ) ) {
echo $_SESSION['errorMessage'];
}
or you can try
POST way
function saveComment(){
$id = isset($_POST["articleId"]) ? $_POST["articleId"] : '';
if ( isset( $_POST['saveChanges'] ) ) {
if ( $_POST['name'] == "" ){
$error = urlencode('Please fill out your name');
header( "Location:".HOME_PATH."/.?action=viewArticle&articleId=".$_POST['articleID']. "&error=" . $error);
}
if ( isset( $_GET['error'] ) ) {
echo urldecode($_GET['error']);
}
I have not tested this but you should get the basic idea of what to do.
When you do a header location your redirecting the user to a new page. Your going to have to either pass the error in the query string or ideally pass it as a variable in the session.
I would suggest doing this all in one file, i.e. The form and the validation as one file.
Then you can do this:
<?php
//set success to 0
$success = 0;
$errormsgs = array();
//check for post
if(isset($_POST['submit'])){
//get the data from the form post and validate it
$valid = validateFuntion($_POST['data'])
//the is function will validate the data. If it is not valid, it will add a message to $errormsgs
//check for errors
if(!$errormsgs){
//data validation was successful, do stuff
}
}//if validation fails, it will fall out of the this code block and move on
?>
<html>
<body>
<?php
//check for errors
if($errormsgs){
$content .= '<ul class="errors">';
foreach($errormsgs as $error){
$content .= "<li>" . $error . "</li>";
}
$content .= "</ul>";
echo $content;
}
?>
<form name="name" action="" method="post">
<input name="name" value="<?= (isset($_POST['data']) ? $_POST['data'] : '') ?>" type="text">
</form>
</body>
</html>
You're redirecting the user to the "error" page with the header statement. The problem is, of course, this is a completely new page, there's no state left over, so none of your variables exist any more.
There's two ways to do it, either pass it on the query string (so add &error=...) and parse that in your template, or save it to the session.
Of course, you should really be doing this before your template is presented using a different means, but that's a complete rework of your code.
header('Location: ' . $uri);
This will miss all the $_POST information.
Don't use $_SESSION as you have been suggested. Session data is shared with all other pages, including the ones open in other tabs. You may get unpredictable behaviour if you use the same trick in multiple places of your website.
An untested better code would be something like this.
session_start();
$data_id = md5( time().microtime().rand(0,100) );
$_SESSION["POSTDATA_$data_id"] = $_POST;
header('Location: ' . $uri."?data_id=$data_id");
In the next page you may retrieve the previous post like this
session_start();
$post = array();
$data_key = 'POSTDATA_'.$_GET['data_id'];
if ( !empty ( $_GET['data_id'] ) && !empty( $_SESSION[$data_key] ))
{
$post = $_SESSION[$data_key];
unset ( $_SESSION[$data_key] );
}
The code above is not tested, you may have to deal with some error before it works.
if u want to carry forward your POST data to another pages ( except the action page) then use
session_start();
$_SESSION['post_data'] = $_POST;
Indeed, you can't redirect POST requests.
Either let your server proxy the request (i.e. make a cURL request to the other site) or create another form, fill it with hidden fields and submit it with Javascript/let the user click.
Alternatively, as #diEcho says, depending on what you're trying to do: sessions.
If you perform a redirect the post will be lost and a GET will occur.
You could save your POST in a SESSION or encode it in the GET (as query string)
You could save the post data in the session, redirect, and then retrieve it back from the session.
session_start();
$_SESSION['POSTDATA'] = $_POST;
header('Location: ' . $uri);
Then in the PHP file for the new location, retrieve the post data like this:
$_POST = $_SESSION['POSTDATA'];
I do use my own simple method.
Just think very logical! For example if you use a text attribute which you want to keep the value of, you can use:
<?php $textvalue = $_POST['textname']; ?>
<input type="text" name="textname" value="<?php echo $textvalue; ?>" />
<br />
//And if you want to use this method for a radio button, you can use:
<?php if(isset($_POST['radio1']){
$selected = "selected";
} ?>
<input type="radio" name="radio1" <?php echo $selected; ?> />
ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.