im very new to PHP, so please excuse me if this is a stupid question.
So here is the scenario.
Im writing a PHP all in one page that gets a random word from an array, scrambles the word, then lets the user guess the word.
now im using the isset(), so it declares the variable, then once submit is clicked, it will get in user input via _POST().
Now the problem
I need the calculated variable to remain constant, but once the page reloads, it regenerates the variable.
is there anyway i can get pass this?
<?php
function GetShuffWord()
{
$arrayName = array('word1','word2','word3','word4','word5');
$randWordIndex = rand(0,4);
$randomWord = $arrayName[$randWordIndex];
$shuffledWord = str_shuffle($randomWord);
return $shuffledWord;
}
if(!isset($_POST['Submit']))
{
define("shuffledWord", GetShuffWord());
$tempWord = shuffledWord;
// showing the user shuffled word
echo " <h1 style='font-size: 50px' align = 'center'> {$tempWord}
</h1>";
}
else
{
$tempWord = shuffledWord;
echo " <h1 style='font-size: 50px' align = 'center'>{$tempWord} </h1>";
echo "else part";
}
?>
another problem is that if i declare the variable in the if, i cannot use variable in the else with out re-generating it.
You can just include the value as a hidden input field in your form.
<input type="hidden" name="myCalculatedValue" value="<?= $tempWord ?>" />
Then when the form is submitted you can just get it via $_POST['myCalculatedValue']
You can use session and put a check that if session has it already dont overwrite.
And when u want to overwrite you can do so as well by passing another flag to the script in your post request.
Related
I'm currently working on a personal content management system project, but I've run into a problem.
<ul>
<?php
if(!$result) { //Check for result
die("You have no pages ☹ Why not create one?");
} else {
while ($pages = mysqli_fetch_assoc($result)) { //Loop through results
?>
<li class="triple"><span><?php echo $pages["title"]?></span><span><?php echo $pages["visible"] ?><span /><form action = "editPage.php" method="post"><input type="submit" value="Edit Page" name="<?php $pages["title"];?>" /></form></li> //Create li elements for each result that gets created
<?php
};
};
?>
</ul>
Basically I'm using a query to results from a MySQL table and make a list of pages, the problem I've run into is that on the end form what I want to happen is I want a session variable to be stored saying which page is going to be edited, but I can't use $_POST in the form at the end to get the name because obviously the name is automatically generated from the table. Each person who uses it would have a different name for a page so I can't just get one name e.g. $_POST['homepage'].
If anyone can offer any advice on how to solve my problem or even how to come up with a better solution to store which page will be edited as it goes onto another page (editPage.php) that would be great.
Use $_SESSION[] to store the data for your $page arrays and access it again on editPage.php. You will need to make sure you call start_session(); on both pages though for it to work as expected. Since you're creating multiple forms and don't know which one will be submitted at the time PHP is running you would need to store all the pages in your $_SESSION and then iterate through them to check for the one which was selected in editPage.php:
$_SESSION['pages'] = array();
while ($page = mysqli_fetch_assoc($result)) {
$_SESSION['pages'][] = $page;
echo "<li class=\"triple\">
<span>".$page["title"]."</span>
<span>".$page["visible"]."</span>
<form action=\"editPage.php\" method=\"post\">
<input type=\"hidden\" name=\"pageID\" value=\"".$page['id']."\">
<input type=\"submit\" value=\"Edit Page\">
</form>
</li>";
}
Then in editPage.php
foreach($_SESSION['pages'] as $page){
if($page['id'] == $_POST['pageID']){ $editpage = $page; break; }
}
// do stuff with $editpage data
Another option would be to use serialize($page) and send the array with the form data in a hidden input element.
<input type='hidden' name='data' value='<?php echo serialize($page); ?>'>
Then you can use $editpage = unserialize($_POST['data']); to turn it back into an array in editPage.php.
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.
I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.
<?php session_start();?>
send the color
<br><br>
<?php
#$_SESSION['color'] = $_GET['color'];
echo $_SESSION['color'];
?>
<br>
<br>
check the session variable
hi,
i need help for the above code.
i want to pass a variable to session.
with above code im doing this but the session variable dissappears when i refresh the page or when i click the bottom link. i want the echo $_SESSION['color']; sticky
what should i do?
with regards
You are assigning value of $_GET['color'] no matter if there is such GET variable or not. Because of this, when there is no $_GET['color'] you are loosing the session variable.
it have to be:
if (isset($_GET['color'])) {
$_SESSION['color'] = $_GET['color'];
}
echo isset($_SESSION['color']) ? $_SESSION['color'] : '';
When $_GET['color'] is empty because color is not in the query string of the URL, you still assign that empty value to $_SESSION['color'].
Don't do that and the value you set won't be overwritten. Nothing was disappearing on its own.
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.