Reload page, keep sessions - php

I'm trying to develop a function where a user can click "Previos week"/"Next week" and that will trigger some $_SESSION variables to change values (dates).
I have this code on absence.php (I know that PRG pattern is not implemented. I have no idea on how to do this but still keep functionality).
<?php
if (isset($_POST['decrease_date'])) {
$monday_value = ($_SESSION['sess_mon'] = strftime("%Y-%m-%d", strtotime("{$_SESSION['sess_mon']} -1 day")) );
}
if (isset($_POST['increase_date'])) {
$monday_value = ($_SESSION['sess_mon'] = strftime("%Y-%m-%d", strtotime("{$_SESSION['sess_mon']} +1 day")) );
}
else {
$monday_value = ($_SESSION['sess_mon'] = date('Y-m-d', strtotime('Monday this week')) );
}
?>
<form action='absence.php' method='post'>
<input type="hidden" name="decrease_date"/>
<input type='submit' value='Previous'>
</form>
<form action='absence.php' method='post'>
<input type="hidden" name="increase_date"/>
<input type='submit' value='Next'>
</form>
Now I would like to reload the page (with jQuery location.reload()-function) but still keep the $_SESSIONs what was active at the moment before the page was refreshed. Currently this will "reset" since there is no $_POST.
Ideally I would like to send the <form action'#'> to another page. However when you first enter absence.php the dates should be reset.
How would I do this?

change
session_start();
into:
if (!isset($_SESSION)){
session_start();
}

Instead of reloading, can't you just submit form by jquery $("form#frmDate").submit(); Don't forget to give ID to your form frmDate.
Is this what you are looking for?

Related

Saving form information with sessions

I'm trying to use sessions to save form input, but it works only on the last form submitted.
I have an index.php that goes like this:
<?php
session_start();
$_SESSION['number-of-sessions'] = 0; ?>
...
then, there's a link to form.php:
...
<form action='display.php' method='post'>
<input type='text' name='name'/>
<input type='text' name='id'/>
<input type='submit' value="Submit"/>
...
And here's display.php:
<?php
session_start();
$_SESSION['number-of-sessions']++;
$_SESSION[$_SESSION['number-of-sessions']] = $_POST;
?>
...
<?php
for($i = 1; $i <= $_SESSION['number-of-sessions']; $i++) {
print_r($_SESSION[$i]));
}
?>
// another link that goes back to form.php
So basically, it always prints the last form submitted and the others are just blank space.
Is there any other way of doing this or am i doing it right?
p.s: i can't use databases.
Not surprisingly, you have a new $_SESSION for each session, so stocking any information that way won't work.
If you want to persist data across sessions, you have to persist it somewhere. Consider writing it to a file if you can't use databases, for example.

on page refresh POST array do not get empty

I created a form in php with action as the same page url and method as POST
<?php
if(isset($_POST['submitted']) && $_POST['submitted'] != ''){
echo $_POST['fname'];
echo "<br />";
echo $_POST['lname'];
echo "<br />";
echo $_POST['submitted'];
}
?>
<h1>testing...</h1>
<form action="test.php" method="POST">
First Name: <input type="text" name="fname" />
Last Name: <input type="text" name="lname" />
<input type="submit" name="submitted" />
</form>
When I enter data and submit it, page shows the data as I printed the data. But when I refresh page the data still exists, I want the data to be shown only when I click submit.
Can anybody help me in this?
Am I doing something wrong.
AFAIK. This is a standard browser behavior to repeat last request with f5 button.
My understanding for what do you need to prevent it. It's to prevent 'spam'.
So, you need to understand that first submit was already made.
As test idea you can add timestamp for send button and check it on send. In this case timestamp from button and on send will be different for refreshing
I figured out that
0) {
$_SESSION['shout'] = $_POST['shout'];
header("HTTP/1.1 303 See Other");
header("Location: http://$_SERVER[HTTP_HOST]/echochamber.php");
die();
}
else if (isset($_SESSION['shout'])){
$echoedShout = $_SESSION['shout'];
/*
Put database-affecting code here.
*/
session_unset();
session_destroy();
}
?>
OR I did that in codeigniter using set_flashdata which stores session data for next request only.

PHP Get Date and Time when a button is clicked and store it in a variable

I would love to know if this is possible using PHP. For an instance, I want the current date and time be stored on a variable once I click the submit button. Here is what I have in mind:
<?php
if ($_POST["submit"] == 'submit')
//store the variable here
?>
<form action ="" method="post">
<input type="submit" name="submit">
</form>
I am quite new to PHP, hope you guys can help me! cheers.
This might be sufficient for your needs, give it a shot. You can change up the format of date() by passing different parameters to it (like switch up month and day and so on). Check up on that here. Also, don't forget to set your timezone.
<h2>Click</h2>
<form action="" method="POST">
<button name="click" class="click">Click me!</button>
</form>
<?php
if(isset($_POST['click']))
{
$date_clicked = date('Y-m-d H:i:s');;
echo "Time the button was clicked: " . $date_clicked . "<br>";
}
?>
The date is stored in the variable $date_clicked if you didn't notice. You can do whatever you want with that afterwards, like store it in your MySQL database.
you can do it like this:
<?php
if (isset($_POST["submit"])){
// getting current Date Time OOP way
$currentDateTime = new \DateTime();
//set timeZone
$currentDateTime->setTimezone(new \DateTimeZone('America/New_York'));
$dateTime = $currentDateTime->format('l-j-M-Y H:i:s A');
}
?>
<form action ="" method="post">
<input type="submit" name="submit">
</form>

Reload same page after form subit in HTML/PHP

I am using a get method to select options with years and months. The URL after submitting this selection looks as follows:
www.mywebsite.com/transactions/?yr=2013&mo=6
I can reload this page and the selection is still there. However, when i submit a form to add a record, the page reloads as follows:
www.mywebsite.com/transactions/?#
And the selection is gone. How can I keep the seletion and reload the exact same url after submitting the form?
I am using the following code:
<form action="?" method="post">
<SELECT options with different inputs>
<input type="submit" value="Add">
</form>
In my PHP it looks the following:
header('Location: ?yr='. $GLOBALS['yearselect'] .'&mo=' . $GLOBALS['monthselect']);
It creates the right URL after submit, only the global variables are not updated. I defined those as follows:
$GLOBALS['monthselect'] = date('m');
$GLOBALS['yearselect'] = date('Y');
And they are changed when I select an option.
You could traverse through submitted variables and add them to the HTML code.
<form action="target.php?var1=<?= $_GET["value2"]; ?>&var2=value2" method="get">
Or just use $_SERVER['REQUEST_URI'] inside action="".
Your form element probably has an attribute action="#".
You could replace this with the original request uri (assuming you use the POST method, if you use GET the query parameters in the form's action attribute will be overridden in most browsers.
<form method="POST" action="<?= $_SERVER['REQUEST_URI'] ?>">your form</form>
In your PHP code, after you get the values by GET method, use the header() function as :
header("Location: www.mywebsite.com/transactions/?yr=2013&mo=6");
It will redirect to the page with the form.
EDITED:
This is a sample code for your need:
<?php
$years=array(1999,2000,2001,2002,2003,2004);
if(isset($_POST['year']))
{
/*
Do your coding here
*/
echo <<<EOT
<form action='{$_SERVER['PHP_SELF']}' method='POST'>
<select name='year'>
EOT;
for($i=0;$i<6;$i++)
{
if($years[$i]==$_POST['year'])
echo "<option value='{$years[$i]}' selected='selected' >{$years[$i]}</option>";
else
echo "<option value='{$years[$i]}'>{$years[$i]}</option>";
}
echo <<<EOT
</select>
<input type='submit' value='Add'>
</form>
EOT;
}
else
{
echo <<<EOT
<form action='{$_SERVER['PHP_SELF']}' method='POST'>
<select name='year'>
EOT;
for($i=0;$i<6;$i++)
{
echo "<option value='{$years[$i]}'>{$years[$i]}</option>";
}
echo <<<EOT
</select>
<input type='submit' value='Add'>
</form>
EOT;
}
?>
It will print the first value of the drop-down list on the first time, and after that it'll save the values.
Inside form tag action attribute should b set to the page which handles your request,i think u have set action='#' .
Please specify more detail.so that i can help u

updating wrong record in database after pressing button

I am busy making a new website, but I ran into a little problem today.
I will try to explain it as good as possible.
My website displays a random message every time you refresh the page, you can then click a button that says you like that message.
Now the problem is that when you click the button to like the message the page reloads (because of the form tag) and the like will go to the next message that is displayed.
I have no idea how to solve this so I hope you guys out there can help me with this.
I will post the code below here:
The bit that updates the database after you pressed the like button:
if(!empty($_POST["submit"]))
{
$id = $random['id'];
$query = "UPDATE `quotes` SET `likes` = likes + 1 WHERE `id` = $id";
$result = mysql_query($query);
if ((mysql_error()!=""))
{
$ANTW = mysql_error();
echo ("Cause of the error: " . $ANTW);
}
else
{
echo "It worked!";
}
}
The like button:
<form name='' method='post' action=''>
<input class='like' type='submit' name='submit' />
</form>
I hope that this if enough for you to solve the problem, if not let me know and I will post more code.
Dennis
UPDATE:
Hi guys, Thanks for all of the quick and good advice it worked the way you told me. Thanks
Save your id in a hidden input:
<form name='' method='post' action=''>
<input type="hidden" value="<?php echo $random[$id]; ?>" name="like" />
<input class='like' type='submit' name='submit' />
</form>
And in your PHP code assign:
$id = $_POST['like']; // your like id you passed by the form (input type hidden)
Send the id in submit form using a hidden field like
<input type="hidden" name="myid" value="YOURID">
and in the next page fetch the previous id using
$_POST['myid']

Categories