cannot put new string into array - php

I have a form when the user types something in, it will appear on the screen. I kept the text that the user typed in a variable called $output, then I tried to put each $output into an array called $arrayText, my objective is to have the user type in something and click a button, then the user's text appears on the screen and when he tries for the second time, the first text is still there while the new one will be on the next line. However, it works only for the first time. For the second time, it replaces the second text with the old one, here is my code
if (isset($_POST['putContents'])) {
$output = $_POST['contents'];
test();
}
function test()
{
static $arrayText = array();
global $output;
$arrayText[]= $output;
for($i = 0; $i < count($arrayText); $i++){
echo $arrayText[$i];
echo "<br>";
}
}
}
?>
thanks for any help in advance

You can't "collect" the user input line-by-line into an array after each time he presses the submit button. The lines must be persisted (stored) somewhere. You can store each line as a record in a database or in a session cookie as suggested. I would persist the state by storing the entered lines in hidden input tags inside your form:
<input type="hidden" name="line[0]" value="What the user typed in first" />
<input type="hidden" name="line[1]" value="The second line that was typed in" />
<input type="text" name="contents" value="" />

By executing a second time your script your $_POST will only have the values of your last submit which in your case will override your array.
If you want to store data beyond the current process you'll have to store the date somewhere other then the $_POST global.
I'm suggesting you use sessions for this as a database query would certainly over blow your needs.
Use:
session_name("admin");
session_start();
if(empty($_SESSION["yourOldText"])) $_SESSION["yourOldText"]=$_POST["userinput"];
and if you want to access your old data then you can just use $_SESSION["yourOldText"]

Related

How to auto refresh list of session array items on submit?

I am working on a school comparing website. For this I need a plugin that handles that function. I save session data as school IDs so it can be passed on in the comparing table after choosing the schools.
Tasks that I have trouble with:
"Add button" - add post/school ID to session array - $_SESSION['schools']
Dashboard at the top - echo $_SESSION['schools'] values (just for user experience list the schools that are currently in the list)
when "Add button" is pressed update the dashboard list automaticly. Preferably not the whole page.
My attempt so far:
First of all I have I commented PHP form action:
<?php session_start();
$schools = array('post_id');
//If form not submitted, display form.
if (!isset($_POST['submit_school'])){
//If form submitted, process input.
} else {
//Retrieve established school array.
$schools=($_POST['school']);
//Convert user input string into an array.
$added=explode(',',$_POST['added']);
//Add to the established array.
array_splice($schools, count($schools), 0, $added);
//This could also be written $schools=array_merge($schools, $added);
}
$_SESSION['schools'] = $schools;
?>
Next up is the form itself:
<form method="post" action="http://henrijeret.ee/7788/temp_add_button.php" id="add_school">
<input type="hidden" name="added" value="Value" size="80" />
<?php
//Send current school array as hidden form data.
foreach ($schools as $s){
echo "<input type=\"hidden\" name=\"school[]\" value=\"$s\" />\n";
}
?>
<input type="submit" name="submit_school" value="Lisa võrdlusesse" />
</form>
And for the dashboard I use:
<?php
foreach($_SESSION['schools'] as $key => $value){
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>
This is just a prototype to get my head wrapper around the task ahead of me...
Problems
Something does not feel right.. :P
When I submit the form, then the first change is not made. When I press it the second time, then it will update the the list leaving out the very last string. When refreshing then whole page, then the last one pops up
I very appriciate the advice on this long topic.. Maby I do not know where to look, but I am a little stuck with searching a solution..
Link to my running code http://henrijeret.ee/7788/
You're submitting the form on the first run.. if you will check it your URL changes and on the next run.. since you got this
//If form not submitted, display form.
if (!isset($_POST['submit_school'])){
//If form submitted, process input.
} else {
//Retrieve established school array.
$schools=($_POST['school']);
//Convert user input string into an array.
$added=explode(',',$_POST['added']);
//Add to the established array.
array_splice($schools, count($schools), 0, $added);
//This could also be written $schools=array_merge($schools, $added);
}
it will go to else statement because POST is already set.
Try this:
//If form not submitted, display form.
if (!isset($_POST['submit_school'])){
//If form submitted, process input.
} else {
//Retrieve established school array.
$schools=($_POST['school']);
//Convert user input string into an array.
$added=explode(',',$_POST['added']);
//Add to the established array.
array_splice($schools, count($schools), 0, $added);
//This could also be written $schools=array_merge($schools, $added);
$_SESSION['schools'] = $schools;
}

How to keep variable constant even after page refresh in PHP

I'm making a simple hangman application and I have my php file and a separate .txt file holding the words, one on each line.
What I want is for the $word variable to remain constant even after the page refreshes since I was planning on using a GET or POST to get the user's input.
In the example code below I want $word to stay the same after the form is submitted.
I believe it's a simple matter of moving code to another place but I can't figure out where any help for this PHP noob would be appreciated!
wordsEn1.txt:
cat
dog
functions.php:
<?php
function choose_word($words) {
return trim($words[array_rand($words)]);
}
?>
hangman.php:
<?php
include('functions.php');
$handle = fopen('wordsEn1.txt', 'r');
$words = array();
while(!feof($handle)) {
$words[] = trim(fgets($handle));
}
$word = choose_word($words);
echo($word);
echo('<form><input type="text" name="guess"></form>');
?>
use sessions:
session_start(); // in top of PHP file
...
$_SESSION["word"] = choose_word($words);
$_SESSION["word"] will be there on refresh
if you care about the "lifetime", follow also this (put it just before session_start)
session_set_cookie_params(3600,"/");
It will hold an hour for the entire domain ("/")
You could use a hidden input:
<form method="POST">
<input type="text" />
<input type="hidden" name="word" value="<?php echo $word; ?>" />
</form>
...and on the next page:
if(isset($_POST['word'])) {
echo $_POST['word'];
}
Or you could use a PHP $_COOKIE, which can be called forever (but kind of a waste if you just want it on the next page):
setcookie('word', $word, time()+3600, '/');
...and on the next page:
echo $_COOKIE['word'];
Just use hidden type forms for that issue.if we put it into session while page refreshes its hide also. if you can store that value in hidden form field it was stored and retrived any time .

Refresh page without losing the Post value

How do I maintain the $post value when a page is refreshed; In other words how do I refresh the page without losing the Post value
This in not possible without a page submit in the first place! Unless you somehow submitted the form fields back to the server i.e. Without Page Refresh using jQuery etc. Somesort of Auto Save Form script.
If this is for validation checks no need for sessions as suggested.
User fills in the form and submits back to self
Sever side validation fails
$_GET
<input type="hidden" name="first"
value="<?php echo htmlspecialchars($first, ENT_QUOTES); ?>" />
validation message, end.
alternatively as suggested save the whole post in a session, something like this, but again has to be first submitted to work....
$_POST
if(isset($_POST) & count($_POST)) { $_SESSION['post'] = $_POST; }
if(isset($_SESSION['post']) && count($_SESSION['post'])) { $_POST = $_SESSION['post']; }
You can't do this. POST variables may not be re-sent, if they are, the browser usually does this when the user refreshes the page.
The POST variable will never be re-set if the user clicks a link to another page instead of refreshing.
If $post is a normal variable, then it will never be saved.
If you need to save something, you need to use cookies. $_SESSION is an implementation of cookies. Cookies are data that is stored on the user's browser, and are re-sent with every request.
Reference: http://php.net/manual/en/reserved.variables.session.php
The $_SESSION variable is just an associative array, so to use it, simply do something like:
$_SESSION['foo'] = $bar
You could save your $_POST values inside of $_SESSION's
Save your all $_POST's like this:
<?php
session_start();
$_SESSION['value1'] = $_POST['value1'];
$_SESSION['value2'] = $_POST['value2'];
// ETC...
echo "<input type='text' name='value1' value='".$_SESSION['value1']."' />";
echo "<input type='text' name='value2' value='".$_SESSION['value2']."' />";
?>
Actually in html forms it keeps post data.
this is valuble when you need to keep inserted data in the textboxes.
<form>
<input type="text" name="student_name" value="<?php echo
isset($_POST['student_name']) ? $_POST['student_name']:'';
?>">
</form>
put post values to session
session_start();
$_SESSION["POST_VARS"]=$_POST;
and you can fetch this value in another page like
session_start();
$_SESSION["POST_VARS"]["name"];
$_SESSION["POST_VARS"]["address"];
You can use the same value that you got in the POST inside the form, this way, when you submit it - it'll stay there.
An little example:
<?php
$var = mysql_real_escape_string($_POST['var']);
?>
<form id="1" name="1" action="/" method="post">
<input type="text" value="<?php print $var;?>"/>
<input type="submit" value="Submit" />
</form>
You can use file to save post data so the data will not will not be removed until someone remove the file and of-course you can modify the file easily
if($_POST['name'])
{
$file = fopen('poststored.txt','wb');
fwrite($file,''.$_POST['value'].'');
fclose($file);
}
if (file_exists('poststored.txt')) {
$file = fopen('ipSelected.txt', 'r');
$value = fgets($file);
fclose($file);
}
so your post value stored in $value.

keep past value of variable

I put a variable (price) to a html form from database.
then user changes the price and submit the form and variable is updated in database.
I want to keep previous value (last state and show it in the form) but if I update the form variable keeps updating.
What is best way to remember previous value of variable (in array for example) ?
If you're updating this data in an actual Database, you should create a parallel table that holds the value of the previous row.
Otherwise, if you're updating only an array, you can just create a copy prior to updating the array: http://codepad.org/SvlasJ7f
<?php
$array = array('Old Value');
$lastarray = '';
updateArray($array,'New Value');
function updateArray(&$a,$v) {
$GLOBALS[lastarray] = $a;
$a = array($v);
}
?>
If you want to retain the LAST value AND display it on the screen, combine the two! Just display the previous value, in a readonly input field in your form. That way, you will still have the previous value every time the form is submitted.
<form action="process.php" method="POST">
<input type="text" name="Current" value="...">
<input type="text" name="Last" value="..." readonly="readonly">
</form>
Or am I missing something?

PHP quiz send data to next page

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.

Categories