Cannot seem to use $_POST twice on the same page - php

I am trying to access different elements in an XML so I can edit them or add new ones from within a web page. I'm using PHP to loop through the parent tags and display in a select list then have submit button to POST the element selected - no issue.
I then use PHP to find all the names of the selected elements children, and display those names in another select list form. This displays the children in the list correctly however when I hit submit it displays correctly if I echo $_POST("Section") but clears the previous $_POST("Page").
I think this has something to do with using action="", but interestingly if I change one them to GET it works as intended. I actually want a 3rd step into lower children again, so cannot use that solution as a dodgy workaround.
I wont post XML as it has sensitive data in it and you can just trust I am stepping through that fine, it's the php clearing $_POST that is the big issue for me.
Please go easy - I literally learnt how to make a basic html webpage in april.
Tried a bunch of different form action including the .php it is on, and also
<?php echo $_SERVER['PHP_SELF']; ?>" >
As stated before - using one as GET and one POST seems to solve the issue
<?php
//pages processing and put into an array
$pages_array = array();
$xml = simplexml_load_file('XML/links.xml') or die ("Failed to load");
foreach($xml->page as $page){
array_push($pages_array, $page->name);
}
$pagecount = count($pages_array);
?>
<form name="page_select" method="POST" action="">
<select name="Page">
<?php
for ($i = 0; $i < $pagecount; $i++){
print '<option>'.$pages_array[$i].'</option><br>';
}
?>
</select>
<input type="Submit" name="edit_page" value="edit"/>
</form>
<br></br>
<?php
// save page selected into $pg and display page being edited
$pg = $_POST["Page"];
echo 'YOU ARE EDITTING PAGE: '.$pg;
?>
****** THEN FURTHER DOWN THE PAGE *****
<?php
// section processing
$section_array = array();
$xml = simplexml_load_file('XML/links.xml') or die ("Failed to load");
foreach($xml->page as $page){
if($page->name == $pg){
foreach($page->sections->section as $section){
array_push($section_array, $section->name);
}
}
}
$sectioncount = count($section_array);
?>
<form name="section_select" method="POST" action="">
<select name="Section">
<?php
for ($i = 0; $i < $sectioncount; $i++){
print '<option>'.$section_array[$i].'</option><br>';
}
?>
</select>
<input type="Submit" name="edit_section" value="edit"/>
</form>
<br></br>
<?php
$sct = $_POST["Section"];
echo 'YOU ARE EDITTING SECTION: '.$sct;
?>
I want output to remember both arrays after the second form is submitted, however due to the first POST variable being wiped it means I also lose the second array since when it gets back to pushing to $section_array $page->name can never = $pg since $pg is now empty

Every time you submit a form, the page is reloaded and PHP will only have access to the POST variables from the form that triggered the page reload. This means that as your second form is submitted, $_POST['Page'] ceases to exist.
There are many ways around this problem, here is a fairly simple one. In your second form, create a hidden input that contains the value of the $_POST['Page'] variable. That way, when the second form is submitted, the Page value will be propagated to the next step of the process. Adding this code to your section_select form should suffice:
<?php
if(isset($_POST['Page'])) {
?>
Page: <?php echo $_POST['Page'] ?>
<input type="hidden" name="Page" value="<?php $_POST['Page'] ?>" />
<?php
}
?>

Related

Get the dynamically generated name from the form into the $_POST

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 &#9785 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.

Updating hidden input depending on what user has checked

I've created a test system that has multiple steps (using jquery) allowing users to check checkboxes to select their answers, with a summary page and a final submission button... all within a form. I now want to create the scoring system.
1) Firstly this is the code (within a loop) that grabs the answers from Wordpress for each question:
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo $row['answer']; ?>" />
2) In Wordpress next to each answer is a dropdown with a yes or no option to mark whether the answer is right or wrong. This is output in the following way:
<?php $row['correct']; ?>
3) Each correct answer the user checks should be worth 1 point. The passmark is determined by the field:
<?php the_field('pass_mark'); ?>
4) I want it to update a hidden field with the score as the user checks the correct answer:
<input type="hidden" value="<?php echo $score; ?>" name="test-score" />
How can I update the hidden field with the user score as the user is checking the correct answer? I'm not sure what to try with this to even give it a go first!
Ok, everyones spotted a big hole in this. I'm completely open to doing it a hidden way so people can't check out the source. The type of user this is targeted at wouldn't have a clue how to look at the source but might as well do it the right way to start with!
The whole test is within a form so could it only update the hidden field on submit?
I still need some examples of how to do it.
In my opinion you should use sessions for that purpose, because any browser output may be saved and viewed in ANY text editor. This is not right purpose oh hidden input elements. You use hidden inputs when you need to submit something automatically, but never use it when processing some important data.
Mapping your questions and answers via id will allow you not to reveal real answers and scores in HTML.
Just a very simple example how to do that:
<?php
$questions = array(
125 => array("text"=>"2x2?", "answer"=>"4", 'points'=>3),
145 => array("text"=>"5x6?", "answer"=>"30", 'points'=>2),
);
?>
<form method="post">
<?php foreach ($questions as $id => $question): ?>
<div><?php echo $question['text'] ; ?></div>
<input type="text" name="question<?php echo $id ; ?>"/>
<?php endforeach ; ?>
<input type="submit" value="Submit"/>
</form>
/* In submission script */
<?php
if (isset($_POST['submit'])){
foreach($questions as $id => $question){
if (isset($_POST["question{$id}"])){
$answer = $_POST["question{$id}"] ;
if ($answer === $question['answer']){
$_SESSION['score'] += $question['points'] ;
}
}
}
}
Spokey is right - the user would be able to cheat if your score it on the client side like using the method you suggested.
Instead, either user a JQuery $.post call to post each answer and then store the score in a PHP Session. Or just wait until the entire form is submitted and evaluate the score of the form as a whole on the server side.
* Update *
You have to submit the form to a script that can evaluate the form. So say it gets submitted to myForm.php
In myForm.php, get the post vars:
$correct_answers = $however_you_get_your_correct_answers();
//Assuming $correct_answers is a associative array with the same keys being used in post -
$results = array();
if($_POST){
foreach ($_POST as $key=>$value) {
if ($_POST[$key] == $correct_answers[$key]){
$results[$key] = 'correct';
}
else $results[$key] = 'incorrect';
}
}
This is untested, but it should work.

Overwriting PHP variable and remembering it

So I have some data in MySQL being shown on my PHP page inside a table. I've set it up so that each page only displays 3 results each (temporary until it goes live, then it will be more). Everything works fine and it displays those 3 results on each page just fine.
What I want to do is be able to change the amount of results on each page right from the main PHP page. I can change the amount shown on that one page, but as soon as I go to page 2, it resets to 3 results. How can I remember the number stored in the variable, and display it on every page? I tried using SESSIONS, but I couldn't get it to work. I'm still a beginner btw.
$item = $_REQUEST['item'];
if(isset($_REQUEST['item'])){
$limit=$item;
}
else{
$limit=3;
}
//A few lines down -->
<form action="<?php $_SERVER['REQUEST_URI']?>" method="post">
Items: <input type="text" name="item">
<input type="submit" name"go" value="Go">
</form>
You could add SESSION use this way:
$item = $_REQUEST['item'];
if(isset($_REQUEST['item'])){
$limit=$item;
$_SESSION['item_limit'] = $limit;
}
else{
// If we find a limit set in the session use that
if (!empty($_SESSION['item_limit']) {
$limit = $_SESSION['item_limit'];
}
else {
$limit=3;
}
}
If you don't need to remember the value the next time the user visits the page you can simply output the $limit as a value attribute for the "item" input.
Items: <input type="text" name="item" value="<?php echo $limit; ?>">

Extract value from select/option tag in php?

I am not exactly how to do it and how to word the question, so i shall try my best (PS: i'm new to web dev, so please be clear in your answers if you could).
So, I have got a drop down menu with the list names, which are taken from my database. In that database i have a table with names column (the ones that are rendered to the dropdown box) and relevant information to those names. Now, I want that relevant information to appear below in a tag when a user choose one of those names. I also cannot use the form.submit() method because my submit button is already taken for something else.
Here is the code to that bit:
<form name="name_choice" method="post" action="index.php">
<select name="names" onchange="form.some_method()">
<option value="NULL" selected="selected">--Select name--</option>
<?php
for ( $i = 0; $i < $numrows; $i++ ) { //for all the columns, iterate and print out
$id_names = mysql_result($result, $i);
echo "<option value='".$id_names."'>".$id_names."</option>";
}
?>
</select>
</form>
So the bit above works fine, but the "some_method()" is my problem, i don't know what to trigger to display the text in the div below the drop down box (code is below for it):
<div class="information"> <!--if the name is chosen ONLY!-->
<?php
if($_POST['names'] == "NULL") {
echo '<p>Please select an option from the select box.</p>'; //this bit is for testing
}
else {
echo '<p>You have selected: <strong>', $_POST['names'], '</strong>.</p>';
//and then how to echo the relevant information?:(
}
?>
</div><!--end of possible info-->
onchange is a JavaScript event. PHP can't do realtime processing of form data, as it sits on the server and the form is on the client. You can sort of do it by using AJAX and passing the form data as the user types, but that would be a lot more work than is needed. Take a look at JavaScript form validation posts to get yourself headed on the correct path.

PHP drop down and Session question

What really needs to happen here is.. A session takes my data from the drop down listed below. Its gonna take it to the process page then bring it back to this page with a header on the process page. Then when it gets back to the first page the dropdown will populate with the session or the same client as when I left that page and the on change of the drop down will work. Can anyone help me with this. Thank you Right now this returns the client to the drop down but the onchange for the drop down does not work which is what I really need to work.
session_start();
$current = isset($_SESSION['ClientNamefour']) ? $_SESSION['ClientNamefour'] : 0;
while ($row = mysql_fetch_array($result)) {
$id = $row["Client_Code"];
$thing = $row["Client_Full_Name"];
$value = "$id, $thing";
$sel=($id==$current)?'SELECTED':'';
$options4.="<OPTION $sel VALUE=\"$value\">".$thing;
}
?>
<form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<select name="ClientNamefour" onchange="this.form.submit()">
<option value=0>Client
<?php echo $options4?>
</select>
</form>
Process page header
session_start();
$_SESSION['ClientNamefour'] = $_POST['txtclientcode'];
// Do the redirect
// Do the redirect
header("Location: test.php");
exit();
I don't know your question or problem but I just guess that it should be
$_SESSION['ClientNamefour'] = $_POST['ClientNamefour'];
instead of
$_SESSION['ClientNamefour'] = $_POST['txtclientcode'];
Also don't forget to put closing </option> tags into your code.
Of course you have to send the the form data to the process page, but
<form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
looks like the data gets send back to the same page.
And never trust data submitted by the user.
Edit:
Try:
onChange="Javascript:document.forms[0].submit()"
or
onChange="Javascript:document.forms['form'].submit()"
But that is only what I found using Google.

Categories