How to keep url data when going to another page - php

I have url variables that was submitted from a form from the previous page. So my url looks something like site.com/submitted.php?first_name=hello&last_name=bye.
Now I am using a link to keep my submitted variables while I go to my second page
<a href="secondPage.php?first_name=hello&last_name=bye>pageLink</a>
On this second page, it's basically a drop-down using the select tag with a submit button that generates a table from mysql server which then links back into the same page. It looks like:
<FORM ACTION="secondPage.php?first_name=hello&last_name=bye" METHOD="GET">
<select name='selectedOption' >
<option value="op1">option1</option>
<option value="op2">option2</option>
<option value="op3">option3</option>
</select>
<INPUT TYPE="SUBMIT" VALUE = "Search">
</FORM>
But lets say I choose option1 and submit, my url does not keep the variables first_name and last_name but it just replaces it :
secondPage.php?selectedOption=op1
instead of:
secondPage.php?first_name=hello&last_name=bye&selectedOption=op1
Any help is appreciated.

I'm not sure how you want to pass data around but here is a suggestion to get the values you want with php.
Change this:
<FORM ACTION="secondPage.php?first_name=hello&last_name=bye" METHOD="GET>
to this:
<form action="secondPage.php" METHOD="post">
Your code for secondPage.php coud look something like this:
// the 'if' statements aren't necessary. just an idea for simple server-side
// validation
if(isset($_REQUEST['selectedOption']) && $_REQUEST['selectedOption'] != ''){
$option = $_REQUEST['selectedOption'];
}
if(isset($_REQUEST['first_name']) && $_REQUEST['first_name'] != ''){
$fname = $_REQUEST['first_name'];
}
if(isset($_REQUEST['last_name']) && $_REQUEST['last_name'] != ''){
$lname = $_REQUEST['last_name'];
}
All the values you need to do whatever with are now in $option, $fname, and $lname
You say your new to php, welcome :), and don't ever trust user input. You should take some time and read about SQL Injection.
Hope some of this helps and good luck.

ON THE SECOND PAGE. In form make two hidden fields <input type="hidden" value="<?php echo $_REQUEST['first_name'] ?>" name="first_name"/> and
<input type="hidden" value=""<?php echo $_REQUEST['last_name'] ?>"" name="last_name"/>
my suggestion use post method

Basically, I've been working myself with something exactly like that, but I've found a great solution and a great approach in my own opinion.. let me give you some bit and piece of code as an example if you don't mind ^_^..
to be organised and clear what you did is : -
##**FIRST PAGE** : -
the url: - secondPage.php?first_name=hello&last_name=bye <--- this was the result..
Then you travelled to the 2nd page: - <-- result was still associated
##**SECOND PAGE** : -
$firstname = $_GET['first_name'];
$lastname= $_GET['last_name'];
<FORM ACTION="secondPage.php?first_name=<?php echo $firstname; ?>&last_name=<?php echo $lastname ?>" METHOD="POST">
<select name='selectedOption' >
<option value="op1">option1</option>
<option value="op2">option2</option>
<option value="op3">option3</option>
</select>
<INPUT TYPE="SUBMIT" name ="submit" VALUE = "Search">
</FORM>
##**THIRD PAGE** The page that the form is going to go to: -
$option = $_GET ['selectedOption'];
// you can also get the other data on this page through same method i've done on page two..

Related

make an option from a selection tag do action on the whole site PHP

iamiI have a selection tag and and options that can do task in the page , but the problem is that it just does that in just the index page and not and the others... this is my code:
region.php
(isset($_POST["company"])) ? $company = $_POST["company"] : $company=1;
if(isset($_POST['selectedRegion'])){
$region = explode( "|" ,$_POST['selectedRegion']) ;
$_SESSION['regCode'] = $region[0];
$_SESSION['selection'] = $region[1];
$regionCode = $_SESSION['regCode'];
}else if(isset($_SESSION['regCode'])){
$region[1] = $_SESSION['selection'];
$regionCode = $_SESSION['regCode'] ;
}else{
$regionCode = 'DEF';
$_SESSION['regCode'] = $regionCode;
}
<form id="regionSelect" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" onchange="this.form.submit();" >
<select id="selectedRegion" name="selectedRegion" size="1" autocomplete="off">
<option style="border-bottom: 1px dashed #000" value="<?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != 'DEF'){ echo "".$_POST['selectedRegion']."";}?>" selected="selected"><?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != "DEF"){ echo "".$region[1]."";}else{echo "--------";} ?></option>
<option value="ny">New York</option>
<option value="miami">Miami</option>
</select>
<input type="submit" value="Enter Region" />
</form>
process.php
<?php if(!isset($_SESSION)){ session_start();}
if(isset($_POST['selectedRegion'])){
$region = $_SESSION['selectedRegion']=$_POST['selectedRegion'];
if($region == "ny"){
echo "new york selected";
}
if($region == "miami"){
echo "miami selected";
}
?>
The index.php and all the other pages of the site have the region.php and the process.php included, but my problem is that any time that i do a selection it just does the action on the page that is in... and if i want the action to be made in another page i would have to press the option again. is there anyway that i can do the action of my selection work on page change and all the pages of my site? thanks
The solution you are looking for consists of these steps:
you evaluate the selection you receive at session start from the client, according to what the user has chosen. So just what you have so far.
you store that selection in a session variable. See the php documentation for the basic use of a session variable. It just boils down to:
session_start();
$_SESSION['region'] = $_POST['selectedRegion'];
you create a switch statement based on that session variable in all scripts that should react on that user choice:
session_start();
switch ($_SESSION['region']) {
case 'ny':
// do something
break;
case 'miami':
// do something
break;
default:
// do something
}
With this the user has to make his choice only once inside a single session (returning requests). You can offer that selection on the entry page and/or on all pages, just as you like. You can enhance that by storing that inside a persistent user profile, if you have an account management.
In addition some more information, as a reaction to your additional information as you provided by editing your question.
Your general approach is probably into the right direction, great. There are a few issues you have to correct though. I can only hint to them, since you offer only snippets of your scripts.
In 'process.php' you have this line:
$region = $_SESSION['selectedRegion']=$_POST['selectedRegion'];
This is obviously invalid syntax, you cannot have two assignments inside a single statement. At least that does not do what you want it to.
not sure if this conditional really belongs there:
if (isset($_POST['selectedRegion']))
It is fine if 'process.php' is the script meant to SET the session variable. In all other scripts obviously $_POST['selectedRegion'] is not set, since the user did not make a choice / was not offered a choice. So there you cannot test or use that variable, you just use the session variable directly.
there are a few other things, but as said you are on the right track.
This approach does work, it is the "normal" approach to this. So don't get frustrated, you will sort this out. In general: your code is a little confusing, too many separate variables where it is unclear what purpose they save. Why the distinction between region, regionCode and selectedRegion. Why isn't a single variable sufficient? Try to simplify your code, this will help to get this to work.
Value of $_POST['selectedRegion'] will not be available always. You should store this value in session like $_SESSION['selectedReg']=$_POST['selectedRegion']; during the form submission.
<form id="regionSelect" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" onchange="this.form.submit();" >
<option style="border-bottom: 1px dashed #000" value="<?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != 'DEF'){ echo $_SESSION['selectedRegion'];}?>" ><?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != "DEF"){ echo $_SESSION['selectedRegion'];}else{echo "--------";} ?></option>
<option value="ny">New York</option>
<option value="miami">Miami</option>
</select>
<input type="submit" value="Enter Region" />
</form>

Value from dropdown menu is not received when the option has been chosen

The program starts with:
session_start();
$seq = 0;
if (isset($_POST['fname'])) {
echo $_POST['fname']."<br/>";
if (isset($_POST['uid']) {
echo $_POST['uid']."<br/>";
if ($_POST['submit'] && $_POST['edupdel'] != "ABCD") {
echo "postsubmit = ".$_POST['submit']."<br/>";
echo "edupdel = ".$_POST['edupdel']."<br/>";
echo "past submit<br/>";
$opt = $_REQUEST['edupdel'];
echo "OPTION IS = ".$opt;
}
}
}
$fname = $_POST['fname'];
$uid = $_POST['uid'];
$opt = $_POST['edupdel'];
echo $uid.$fname.$opt."<br/>";
echo "*******<br/>";
$seq = $seq + 1 ;
echo "SEQ # is = ".$seq."<br/>";
The idea being: uid and fname are being carried over since the first page and work OK. I can get those values correctly.
The program uses: <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
(GET or REQUEST were options considered but so far no success).
The program has a drop down menu. The first entry "ABCD" id just dummy for now and should not be used in the future.
Please select one of the options:
<select name="edupdel">
<option value="ABCD">ABCD</option>
<option value="edit">EDIT</option>
<option value="update">UPDATE</option>
<option value="delete">DELETE</option>
</select>
The submit goes like this:
<input type="submit" name="submit" value="Submit" style="background-color:#FFFFFF" >
<input type="hidden" name="fname" value="<?php echo $_POST['fname']; ?>">
<input type="hidden" name="uid" value="<?php echo $_POST['uid']; ?>">
<input type="hidden" name="edupdel" value="<?php echo $_POST['edupdel']; ?>">
Now, from the top of my ignorance, I don't know how to retrieve the value for the:<select name="edupdel">
This is not shown when I select, for example, the option EDIT from the menu. I'm not even sure that this is the correct way to obtain the value selected from the drop down list.
So what do I expect: Have uid, fname and the selected option set so I can decide the next step.
Please bear in mind that I'm starting with PHP and the whole shebang, so at this point, after looking in the forum for hours, I decided to take a shot and ask the forum guys what would be the best way to code what I need or just plain point me to some other possible options.
Some debugging data I could get to so far according to the "echos" above:
mary
john
postsubmit = Submit
edupdel =
past submit
OPTION IS = johnmary ( I would expect EDIT or UPDATE or DELETE after the word mary)
*******
SEQ # is = 1
It looks like you have a hidden input field after the submit button with the name edupdel. If this is the case, anything in that input's value will override anything selected in the <select> field.
Try either removing that hidden field, or moving it above the <select> field in the HTML so the select takes precedence.

Set Call to PHP Function, with POST Variables as Parameters, as HTML Form Action

I currently have an HTML file, with a form in it, that when submitted POSTs the form & calls a simple short PHP file that calls a function within another PHP file using the POSTed variables as parameters. The files are both below. What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
Ideally, this would set the call to the function:
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
as the form action. Does anyone know how/if this can be achieved?
HTML:
<FORM ID="FORM1" METHOD="POST" AUTOCOMPLETE="off" ACTION = "writeToDL.php">
<INPUT TYPE="hidden" NAME="Date" STYLE="WIDTH:0px; " MAXLENGTH="8" TITLE="Enter Date" Value="<?php $dt = date('Y-m-d'); echo $dt ?>"/>
<INPUT TYPE="text" NAME="Time" STYLE="WIDTH:70px; " MAXLENGTH="7" ONCHANGE="validateTime();" />
<SELECT NAME = "Result">
<OPTION VALUE = OK></OPTION>
<OPTION VALUE = C>C</OPTION>
</SELECT>
<SELECT NAME = "Participant" STYLE = "WIDTH: 187">
<OPTION SELECTED VALUE = "">Select...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$val = $value->get_id();
echo "<OPTION VALUE='",$val,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
<TEXTAREA NAME='Notes' COLS='28' ROWS='5'></TEXTAREA>
<INPUT TYPE="image" SRC = "images/submit.png" VALUE="Submit Participant"/>
</FORM>
PHP File:
<?php
include_once('database/PE.php');
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
?>
You COULD do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include_once('database/PE.php');
insert_PE(new PE($_POST['Date'],$_POST['Participant'],$_POST['Time'],$_POST['Result'],$_POST['Notes']));
} ?>
<html>
... rest of your page here ...
</html>
That way the PHP code only fires if an POST was actually performed. Some would suggest checking for the presence of a form field, but that's unreliable - you might change the form down the road and forget to update the if(). Checking the request method is guaranteed to be 100% reliable.
What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
No. The client only knows about URIs.
A URI can map to a PHP program. Multiple URIs can map to the same PHP program. You can use logic to determine what functions to run for a given URI. You can't avoid having that logic in your program.
One option is to put method="_the_main_php_file_containing_function_to_be_called_"
I hope it works fine.
I think you could use a hidden field on the form, and populate it with the name of the function you want to run on "destination.php". Then a switch statement on "destination.php" could pull the name of the function from POST variable.

PHP get input , radio , selection data and insert into MySQL table

i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look hereā€”the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.

php how to grab the selected value from a drop down list?

<select name="gamelist" id="gamelist">
<option value="1">Backgammon</option>
<option value="2">Chess</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit" />
i want to grab the selected value and place in in a var
any idea?
thanks
Depends on your form tag.
<form method="post">
Will pass the value to $_POST['gamelist']
While
<form method="get">
Will pass the value to $_GET['gamelist']
Ofcourse, only after hitting the submit button. As morgar stated, this is pretty basic form procession. I doubt you've used google or followed a tutorial, this is almost one of the first things one learn when working with forms and PHP. We arent here to give you full solutions, take this as an example and create the full page yourself:
if($_SERVER['REQUEST_METHOD'] == "Y") {
$choice = $_Y['gamelist'];
// other stuff you want to do with the gamelist value
} else {
echo '<form method="Y" action="file.php">';
// the rest of your form
echo '</form>';
}
Replace Y with either GET or POST.
$choice = $_REQUEST['gamelist']; //works with get or post
$choice = $_POST['gamelist']
if it is a POST, or $_GET if not.

Categories