Keeping some selected options after submitting form - php

Thanks in advance for any suggestions on the following:
I've created a php-page to add works from composers to CDs in a database. It's a combination of two forms and looks like this:
1st form:
Composer : [drop down list] : Select
Some blank space
2nd form:
Title : [drop down list]
Track number : [empty varchar field]
Work : [drop down list]
some other fields
Process button
After selecting a name in the first block (posting to $_SERVER["PHP_SELF"]) I stay on the same page, that name is shown in the blank space in between and the drop down lists are populated with only CD titles and works of the selected composer.
I can then select from the lists and enter other data in the other fields. Hitting the process button posts the data from the second block to another page which will eventually send everything to a table in a MySQL database.
After that I send myself back to the first page with header("Location: the_first_page.php")
So far so good, but upon returning I would like the composer, title and work to be preselected. Now I'm sent to a blank page and have to start from scratch. I think I've seen some solution involving testing $_POST['something'] against <option value> in a drop down list but I can't seem to make that work.
My question is: Is there a way to send $_POST['Title'] and $_POST['Work'] back to the first page somehow? Or is it better to split the two forms over seperate pages?
All help is welcome.

You could use sessions or the post data itself. For using the post data itself, the page where you send the request should be the same and include the script that will process it if there's some data like this:
if (!empty($_POST)) {
include "save.php";
}
// More code...
?>
<select name = "a">
<option <?php if ($_POST['a'] == "test") echo "selected"; ?> value = "test">
<option <?php if ($_POST['a'] == "testb") echo "selected"; ?> value = "testb">
</select>
Of course there are many more ways, but this is just a simple one to get you started. Things to know: you might want to change the variable $_POST and clean it up before using it. In this case it should be fine, but in <input type = "text" value = "<?= $_POST['b']; ?> name = "b">` you have a serious security issue.
For sanitizing the input, you want to sanitize it respect to what you expect. But also, as an EXTRA meassure, you normally want to strip everything that looks like a <script>, onclick ="", ' DROP TABLE users and similar. It's not an easy subject, so I recommend you reading on it, mainly on the XSS attacks which is relevant to showing the text back to the user. While it might seem too much work for this "simple case", it is useful in many more situations.

Use session variables and put conditions for them ... see [ $_SESSION ].

Related

Carrying Variables Between 3 PHP Pages

I am creating a set of 3 pages, each with a dropdown menu. The values from the previous dropdown menus will populate the next dropdown menu. I understand that I must use session variables to hold the value of each dropdown menu into later pages. As a simple test, I echo the variables to see if they have been carried over -- and that's where the problem is.
I have three different files: choose_cc.php, choose_uni.php, and choose_major.php
The value from the dropdowm menu in choose_cc.php does get echoed in choose_uni.php -- however the value from choose_cc.php does NOT get carried over into choose_major.php -- despite me storing it into a session variable.
the flow of pages is like this;
choose_cc.php --> choose_uni.php --> choose_major.php
Each php file has it's own form. The problem lies in when I try to call the value from choose_cc.php into choose_major.php, i have issues.
The name of the form on choose_cc.php is choose_cc.
The name of the form on choose_uni.php is choose_uni.
So for example, in choose_uni.php, I retrieve the value from the dropdown menu on the previous page (choose_cc.php) like this:
$_SESSION['choose_cc'] = trim($_GET['choose_cc']); //fetches cc from previous page
$user_cc = $_SESSION['choose_cc'];
echo $user_cc;
and when I echo it as I did above, it works! Okay perfect!
But when I head onto choose_major.php, I try retrieving the value again from the form, but to no avail like this;
echo $_SESSION['choose_uni']; //this works
echo $_SESSION['choose_cc']; //this doesn't work
I have made sure to store to do session_start() on the beginning of each page as well.
Please help me out! this is driving me insane!
Create a new "see.php" with this:
session_start();
print_r($_SESSION);
and execute it after each choose_cc.php, choose_uni.php and choose_major.php to take a look the session you have after you run your programs.
Simple as this:
a) add session_start(); at the beginning of ALL the involved pages. Some weird stuff happens sometimes if you put a space before it, or even a new line. So be sure it is the very first thing in your script.
<?php
session_start();
?>
b) if needed, check the variable to save into session for not empty(); That way you can be sure the session variable contains something, unless of course you want explicitly to be empty.
c) then load the session variable. You can temporary check it with a var_dump();
<?php
session_start();
if (!empty(trim($_GET['choose_cc'])))
{
$_SESSION['choose_cc'] = $_GET['choose_cc'];
}
var_dump($_SESSION['choose_cc']);
?>

get parameter value from form select instead of querystring

I have a URL structure with query string and parameter called position.
example:
http://computerhelpwanted.com/jobs/?occupation=administrator&position=network+administrator
I also have a form select option drop down list with the form select name of position.
example:
<form action="/jobs/" method="GET" id="menuform">
<select name="occupation" onChange="populate(this.id,\'position\')">
<option selected="" disabled="">Select Occupation</option>
<option value="administrator">Administrator</option>
</select>
<select name="position" onChange="this.form.submit()">
<option selected="" disabled="">Select Position</option>
<option value="network administrator">Network Administrator</option>
</select>
</form>
When the user makes a selection, it sends the option values to the action attribute with the select name="position" as the parameter to use in the query string.
My question is, how do I access the form select values separately from the query string values?
I use the _GET method to call the value from the query string parameter.
example:
$position = isset($_GET['position']) ? ($_GET['position']) : '';
Apparently that gets the value from the URL structure, not the form element. Or maybe it does both, not sure. But testing it, I seem to draw conclusion that it is getting it from URL, not form.
How can I make sure to access the form select value when making my comparisons in my PHP?
Update
The issue I'm having is with my canonical URL set in the header.
<link rel="canonical" href="http://computerhelpwanted.com/jobs/?occupation=administrator&position=network-administrator" />
that link is a indexed link on Google. I know I can just do an htaccess redirect to new link, but I'm just trying to figure out how to display the canonical url for this page.
it should be
<link rel="canonical" href="http://computerhelpwanted.com/jobs/?occupation=administrator&position=network+administrator" />
the only difference is the - and the + in the query string.
Not all of my query strings have the +. Some have the -. But I display the content on both urls whether it has - or +. Either way, both urls get same page content.
But since the canonical is being created dynamically from the URI instead of what the value is from the form element, both content pages have 2 different canonicals.
Using _Get('value') is pulling the value from query string instead of form element. I know this because the form element value has a space between network administrator which gets urlencoded when form submits as network+administrator. So if I can compare to the form element value, I can set the proper canonical.
HTTP is a stateless protocol, you generate the HTML stuff upon invoking the required page, and then it's there. When interacting with a form element, you can put select values from the predefined (built with DOM) options, and you can pass that on to another file for processing. When you pass the values to that processor file, you can do so through various methodologies (for simplicity lets just take a look at the GET and the POST ones).
GET: will convert your form parameters to a url query which you have also posted in your question. When your data arrives in the form of the GET array to your processor file, the file itself has no idea what kind of form it got it from, it only sees the query.
POST: will encode your parameters into the transport layer, having it not apparently visible, however it is still there.
Using GET, you could manually form a query with intendedly invalid or malicious parameters and invoke your processor file with them. POST can also be programatically set to be malicious, but provides a convenient level of obscuration as such, and considering your question, might provide the effect you were looking for ("not directly taking it from the url").
Edit:
Code for simplifying form parameter handling according to visible pattern seen in OP question and comment:
$validKeys = array(
'position',
'occupation'
);
foreach ($validKeys AS $key){
${$key} = isset($_GET[$key]) ? $_GET[$key] : '';
}
/* other processing code */
With the above, if you had lets say 15 input parameters, you wouldn't have to go through all of them one-by-one, as ${$key} allows you to create dynamically named variables, and you just update your $validKeys container (which could also be filled with values held in the database, and not manually controlled). From your updated comment I devised that you might be looking for something like this.
That is because you are are you using GET which can be easily manipulated through URL.
I suggest changing the method to POST. It can be edited though using debuggers.

Form reviewing in HTML

I hope I'm not posting a duplicate question but I've looked around (and googled as well!) and nothing has given me the answer I'm looking for.
I have a form in HTML. When the user submits the form the values get stored with mysql under their user account for the site.
The issue is, I'd like the user to be able to go back and edit the form any time they like.
I could certainly just populate the form with values from php when the users review the form, but it gets tricky when I try to populate a file input field (and the file has been saved in mysql using the blob type). Not to mention that I'd like to do this as cleanly as possible.
Ideally it would be nice if there was a convenient module for reviewing forms that have already been submitted in JQuery per se.
Can anyone offer any advice? Thanks in advance!
Edit:
Here's a good example of what I mean - in chrome if I fill out a form and redirect to the next page after hitting submit, if I hit back I come back to the form and it's still filled out with the information I entered previously! Could I invoke this behaviour whenever I want to, as opposed to only when the user hits back?
You can't pre-fil an <input type="file" . . but surely when they come back to the form, they want to see the file they've uploaded .. this is what you mean right ..
So if its a picture, you could just do: <img src="loadpic.php?id=$var" />
If it's files they've uploaded, just list the file name / date and other data.. etc in some sort of list.
Then you could still show the <input type="file"> .. but with the label, 'add more pictures' or 'add another file'. .etc
Unless someone has a better way, at the moment I'm using a combination of 2 things:
1) Utilizing the $_SESSION variable
2) Setting the "name" attribute of every input in the form to the name of the field it corresponds to in the database.
This way I can loop through all the values dynamically instead of hardcoding them all in. Some input types (like file) are exceptional and will be handled on their own. Other that I can do something like this:
To insert into mysql:
$fields = array();
$values = array();
foreach ($_POST as $field => $value) {
$fields[] = $field;
$values[] = addslashes($value);
}
$fieldString = 'Table_Name('.implode(', ', $aFields).')';
$valueString = "VALUES('".implode("', '", $aValues)."')";
mysql_query("INSERT INTO $fieldString $valueString");
Reviewing the form is somewhat similar. I am using javascript to hook into document.onload. I need to pass javascript the records from mysql so that it may populate the form. Then it's a simple matter of getting elements by their name and assigning them their values that were passed from php.
The easiest way to do it and not have to go back to the database would be to store the values in a session.
<?php $_SESSION['myvalue'] = $inputvalue; ?>
On the html form use:
<input type="text" name="myName" value="<?php echo $_SESSION['inputvalue']; ?>" />
When completed don't forget to unset the session variable:
<?php session_start(); unset($_SESSION['myvalue']); ?>

Is there anyway i could dynamically fetch the value of an <option> and pass it to PHP without using AJAX?

I have two <select> one is category and the second is subcategory.
here is the first <select> for category.
<select name="category" size="10">
<?php foreach($categories->fetch(array('table' => 'categories')) as $category) { ?>
<option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?></option>
<?php } ?>
</select>
now the second <select> i.e subcategory should be hidden initially and when a user click on category <select> based on the value it should populate the value in subcategory.
One way of doing this is via AJAX by passing categoryId as POST Request and getting HTML as response.
however i would like to know if there is any other alternative so that it automatically pass the categoryId value to PHP and unhide the second <select> here is the code of second <select>
<select name="subcategory" size="10">
<?php foreach($categories->fetch(array('table' => 'subCategories', 'categoryId' => $categoryId)) as $subCategory) { ?>
<option value="1"><?php echo $subCategory['name']; ?></option>
<?php } ?>
</select>
the only thing i need here is $categoryId to be populated dynamically. is there any way of doing this?
thank you..
No, there is no way to do what you are suggesting. PHP is only run on the server, so by the time the page is rendered on the client the PHP has already been run.
Your best bet would be what you already suggested, running some AJAX after the first select is changed, sending back the category ID to the server and retrieving what you need to build the second select.
Is there a reason why you don't want to do it this way?
Sukumar has probably suggested the best and most intuitive solution to make it appear as if the data is being loaded dynamically to the user.
The other alternative would be to submit the form when the select box is changed. Once the form has been submitted PHP would pick up the ID from the POST array and then re-populate the sub-category select box. This is often used as a fallback in case the user doesn't have JavaScript enabled.
Structurally, there are three choices to solve this problem:
Use an ajax call to fetch the required data when a user selection is made as jbruno has described.
Submit the whole page to the server, let your PHP see the newly selected option and fill in the newly desired data in a returned page. This will cause the page to refresh so is less ideal than option 1.
Pre-populate the page with all possible data in a javascript data structure so you can use Javascript to just look up the desired category ID in a local data structure, modify the page and never have to talk to the server in order to update the page.
In my opinion, option 3) is the most desirable if the data set required for local lookup is not too large (say under 100k) and it's not too expensive on the server to collect all that data for inclusion in the original page and if the data doesn't change real-time or having data as of the page load time is OK.
If option 3) isn't feasible for any reason, then option 1) is next best. Option 2) is not as good a user experience so it should only be the last resort if you really can't implement options 1) or 3).
You asked more specifically about option 3. I don't really yet understand what the whole data you need looks like. If you really only have four total data types residential_plot, residential_apartment, office_space and showroom, then you can just make those be four keys on an object and store their data that way:
var data = {
"residential_plot": 1,
"residential_apartment": 2,
"office_space": 3,
"showroom": 4
};
The 1, 2, 3 and 4 are just whatever data you want to store for that type. It can be numbers, strings, arrays of data, other objects of data, anything.
To access this, you would do like this:
var id = data.residential_plot;
or
var index = "residential_plot";
var id = data[index];
If you wanted to store the notion of categories and sub-categories, you would need an extra level of objects:
var data = {
"residential": {"residential_plot": 1, "residential_apartment": 2},
"commercial": {"office_space": 3, "showroom": 4}
};
Then, you would access it like this:
var id = data.residential.residential_plot;
or like this:
var category = "residential";
var catType = "residential_plot";
var id = data[category][catType];

Autofill form when link is pressed

I have this webpage. It has a page called "services.php". I have several buttons (made of classes), that belong to different "package" prices i offer.
I want the links that say "Select" to autofill a form in another page, or alternativly in a popup form in the page..
I don't really know how to explain it, but as short as possible:
When link is pressed autofill form (in this or other page) with the type of package they chose. Only text autofill
What you seem to be asking is 'loading' a page pre-filled with specific information, you can do this a number of ways, either by utilizing javascript (like jQuery for instance). Or using your PHP, make links that pass variables (say a flag or a reference to pre-fill the fields -- if you want a popup or next page, etc).
Your url would like like the following for the button that a user presses (button would be a simple http link):
http://mywebsite.com/prefill.php?user=bob&package=2
This would have the values bob as the user that requests it (you can reference an id for user info here as well), and package=2 to designate your package options.
Then on the prefill.php page, you would have something that checks for:
$user = $_GET['user'];
$package = $_GET['package'];
Hope that helps
This will populate form fields with whatever you pass to the autoFill() function. This would be a same page example.
<html>
<body>
<form>
<input type="text" id="packageDescription">
<input type="text" id="packagePrice">
</form>
<script>
function autoFill(packageDescription, packagePrice) {
document.getElementById('packageDescription').value = packageDescription;
document.getElementById('packagePrice').value = packagePrice;
}
</script>
Premium Package<br>
Platinum Package
</body>
</html>
You could do something like this:
<select id="packages">
<option value="package1">Package 1</option>
<option value="package2">Package 2</option>
</select>
Submit
When the link is clicked, the following javascript will fire off:
function submitPackage()
{
var package = $("#package").val();
window.open("http://your-site.com/some-script.php?package=" + package);
}
The above will open a pop up window to a page such as this:
http://your-site.com/some-script.php?package=package1
In some-script.php you will do something like this:
You selected the package: <b><?php echo $_GET['package'];?></b>.
Or:
<?php
//Put the packages in an array:
$packages = array();
$packages['package1'] = 'Package 1';
$packages['package2'] = 'Package 2';
//...
?>
<select id="package">
<?php foreach ($packages as $name => $text):?>
<? $selected = ($name == $_GET['package']) ? 'selected' : '';?>
<option value="<? php echo $name;?>" <?php echo $selected;?>>
<?php echo $text;?>
</option>
<? endforeach;?>
</select>
The above will auto select the package they selected in a dropdown box.
if i understood your problem, you want to fill some input fields with information when the user clicks on some links
i can think of 2 ways of doing this : either have the links point to a page like services.php?req=package1 (or any other url you want) and on that page generate the input fields with the information you need (set the default values in the fields with the ones you want), or, use javascript to change the values of the forms without changing the actual page (either via ajax or predefined values)
for javascript you can use the jQuery framework, it has a pretty extensive community of enthusiasts and plenty of examples to get you started with it.
an example for your case would be
$('#btn1').bind('click', function() {
$('#input1').val("value");
$('#input2').val("value2");
});
replace btn1 with the id of the first button or link you have, input1 with the id of the first input in your form, and value with the value you want
I just did this myself. My solution was with jQuery. Just assign an id to your link. The first ID in the code is the link id and the second is the id for the input element you want to populate.
Here is the script:
<script>
$(document).ready(function() {
$('#link_id').click(function() {
$('#input_id').val( $(this).text() ).keyup();
return false;
});
});
</script>
Hope it works!
I've ran several time into the same issue, so I had to write my own script doing this. It's called Autofiller and its pretty simple but does great job.
Here is an example
http://example.com/?autofiller=1&af=1&pof=package&package=package1
So basically it takes several parameters to init the script:
autofiller=1 - init AutoFiller
af=1 - Autofill after page is loaded
pof=package - Find the parent form element of the select with name attribute package. Works also with input form elements.
package=package1 - Will set the select element's value to package1
Hope it helps you! :)

Categories