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.
Related
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
}
?>
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.
I have researched many places to find an answer to this question, but they never quite answer my real question: What is the best/approved way to move to a new page within the same website? I have read that it is bad to use window.location because search engines will think you are hiding something. But, when I don't want to open a new window (window.open), then I don't know how else to do it. I use href anchors in links and form actions, where appropriate. But when I have menus or buttons with onclick, then I need something else.
Here's an snippet of my code:
my javascript: (with one option commented)
function gotoCat() {
var catcdF = document.catSelect.catcd.value;
<?php
echo "window.location.href='http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF; ";
/*
echo "window.open('http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF,'','resizable=1,scrollbars=1,toolbar=1,top=50,left=300,width=950,height=800,location=0'); ";
*/
?>
}
My dynamic SELECT list in a form (within PHP):
echo " <select name='catcd' id='catcd' size='8' onclick=gotoCat() > \n";
// display list of categories
if ($numcats == 0) { // print message text only
echo "<option value='0' >".$catMsg."</option> \n";
}
else {
for ($i=1; $i<=$numcats; $i++) {
$catcd_db = $catAry[$i][1];
$catName_db = $catAry[$i][2];
echo "<option value='".$catcd_db."'> ".$catName_db." </option> \n";
}
}
echo "</select>";
So, as you can see, I just want a method to allow the user a choice and then automatically go to the correct web page once selected. This is not always in a select list. Often it's when they want to exit or get an error:
if (mysqli_connect_errno()) {
echo "<br/> <p style='text-align:center;'> <button type='button'
class='buttonStyle' style='padding: 4px 20px;' value='Exit' ";
echo "onClick=\"window.location.href='http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev'\" > ";
echo "Exit </button></p> ";
}
I cannot use "go back" because they need to go to a prior page, not the form they came from.
So, unless my navigation methods are really off-the-mark, I guess I need to know the acceptable method for using javascript onClick to move to the next page in the same website. Is window.location okay, or should I use something else?
Any opinions or suggestions are welcome!
To navigate to another page using Javascript, use:
window.location.href = "url";
That's how it's done and there's nothing wrong about it.
For the sake of argument, you could create a hidden link and simulate a click on it, but as I said, there's really no need.
You can use php header('location') instead:
<form action="submit.php">
<input type="hidden" value="test" name="hidden1" />
<input type="submit" Value="Exit" ... />
submit.php
<?php
if (isset($_POST['hidden1'])
{
header('Location: http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev');
exit;
}
?>
More info about header('Location ...');:
http://php.net/manual/en/function.header.php
Instead of a hidden, you use your select's value and get it via the $_POST variable.
I am using Jquery UI Selectable. The user has the option to dynamically add new list items to the original setup.
I would like to include a 'clear' button that will give the user the ability to clear each individual item they created by clicking on an X input submit (img).
HTML (php)
if ($this->session->userdata('inactivefilter') == true) {
$inactivefilter = $this->session->userdata('inactivefilter');
$i=0;
foreach ($inactivefilter as $filter)
{
$filterdash = implode('-', explode(' ', $filter));
echo "<li class='ui-state-default' id='$filterdash'>$filter</li>";
echo "<div id=clear>
<form method='POST' action='".base_url()."main/clear_filter'>
<input type='image' name='filtervalue' value='$i' src='".base_url()."img/board/icons/clear.png'></input>
</form>
</div>";
$i++;
}
}
This is where the list is created. specifically the clear_filter action form.
Clear_filter currently 'attempts' to grab the value of '$i' but I don't know how to pass that correctly.
here is the controller:
public function clear_filter()
{
$i = $_POST['filtervalue'];
$this->thread_model->clear_filter($i);
}
I'll omit the clear_filter model due to its irrelevance to the problem.
Essentially, I just need $i to be picked up based on whatever value is clicked on in the dynamic form on the actual page.
Any help would be appreciated!
Well, it seems like I just had things a bit backwards.
The code was more or less correct.
For Codeigniter, you catch the passed input value=$i by using the name ="filtervalue"
Change the controller code to :
$i = $this->input->post('filtervalue');
and $i is set to whatever value was clicked on.
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.