How to Access $_POST Data Across Multiple Forms - php

For a shopping cart application I'm working on for a class, I have to display information across every step. My problem is that I can display information only from the previous step. For step 1, an item is selected from a radio box. It is then stored like so:
function processStep1() {
//Implemented sessions
$_SESSION["items"] = $_POST["items"];
displayStep2();
}
Step 2 asks for a quantity and then validates it, like so:
function processStep2() {
//Implemented sessions
$_SESSION["quantity"] = $_POST["quantity"];
if ( preg_match('/^\d+$/',$_POST["quantity"]) ) {
displayStep3();
} else {
echo "ERROR: Quantity entered was invalid. Please try again.";
displayStep1();
}
}
(As an aside, I can't seem to get this to just refresh the current step (which would be displayStep2) when the input is not an integer, as I get an error every time I try to do so. If anyone has an answer for why that is, that is additionally helpful.)
But then on Step 3 of the form, I try to run the following line:
<p>You have selected <?php echo $_POST["quantity"] ?> units of the <?php echo $_POST["items"] ?>.<p>
Which responds with an error every time. I have tried various configurations of this same output, and have determined that it will always parse $_POST["quantity"], but never $_POST["items"]. I need it to do both.

Your third form does not "see" $_POST['items'] because it was not submitted to that form. You stored it in a session instead. Start a new session on your third form and request $_SESSION['items'].
Step 1
<form name="step1" method="post" action="whateverPageContaintsProcessStep1.php">
<input type="radio" name="items" value="item1">Item 1
<input type="radio" name="items" value="item2">Item 2
</form>
When we submit our form the $_POST data that is going to be send will be the value of the radio button we selected we selected.
Step 2
<form name="step2" method="post" action="whateverPageContaintsProcessStep2.php">
<input type="number" name="quantity" value="0" />
</form>
When we submit form2 the $_POST data will contain the value of the textbox called quantity, however since this form does not contain the previous radio buttons this value will not be send to the server and therefor we will not be able to access it in 'whateverPageContaintsProcessStep2.php'.

Related

Trying to pass $_POST variables onto another page (Using GAE for deployment)

I am working with multiple forms on a page, where pressing a button will edit that specific post (using the hidden input variable).
I am dealing with two issues here:
When I do press edit, it will grab the last hash from the list (I am using a foreach loop to iterate through the list).
When I do press edit and redirect to the next page, the $_POST variable is deemed null.
Page 1:
foreach ($result as $item) {
echo '
<form method="post" action="editPost">
<input type="hidden" id="messageID" value="' . $messageID . '">
# Print $item iterations here in the form of a html form
<div>
<input type="submit" value="Edit" name="editPost">
</div>
</form>
';
}
Page 2:
if ($_POST['messageID'] == null) {
echo '<script>alert("Key error")</script>';
} else {
# Do things if $_POST['messageID'] is not null
}
You should not add Form inside the loop and input or form with same id or name in loop will confuse html to what should send and may it will send last one,
instead of form in loop just add link of other page with edit record id or hash as in query string
example.com/pagetwo.php?editid=$messageid
and from page 2 you can get that variable useing
$_GET['editid'] or $_REQUEST['editid']
and based on id you need to get data from database and fill in inputs to update it

How to forward information from one page, trough another, and then finally to the third

This is my first post, so excuse me if I will not provide the information correctly.
So my problem is the following:
This is the first form:
<h1>Modificare carti</h1>
<br />
<form action="UTLcrt.php" method="post">
Cod Carte: <br /><input type="numeric" name="cod"><br>
Nume: <br /><input type="text" name="nume"><br>
Autor: <br /><input type="text" name="autor"><br>
Editura: <br /><input type="text" name="editura"><br>
Disponibilitate: <br /><input type="text" name="disp"><br>
Pret: <br /><input type="numeric" name="pret"><br>
<select name="vmod">
<option value="mod">Modificare carte</option>
<option value="str">Sterge carte</option>
<option value="src" >Cauta carte</option>
</select>
<input type="submit">
</form>
The UTLcrt.php contains the following code:
<?php
if (isset($_POST['vmod'])) {
$urls = array(
'mod' => 'modcrt.php',
'str' => 'strcrt.php',
'src' => 'srccrt.php'
);
$url = $urls[$_POST['vmod']];
header("Location: " . $url);
}
?>
And each php page does the following:
modcrt.php changes the entry in our database with the same"cod" with the info provided in the first form
strcrt.php deletes the register in our database, if the "cod" we entered in the first form finds a match
srccrt.php searches in the database if the register with the "cod" provided in the first form was found and shows a possitive message.
My problem is the following: the information I put in the first form doesn't get in the modcrt.php,strcrt.php,src.php pages... the $_Post's are empty...
How to send the information from the first page, trough the second and then to the third?
You can keep them in Session, by using
$_SESSION['info1']=$info1;
The POST values are empty because the third page isn't receiving a POST request. The order of events is this:
User requests the first page.
User POSTs a form to the second page, with values.
Second page tells the user to issue a GET request to the third page.
User requests the third page.
There are a few different ways to keep the information in the chain. You can:
Add it to the query string for the redirect
Store it in session
Store it in a database
etc.
The first one might look like this:
header("Location: " . $url . "?key=value");
Where the key/value pair is similar to those in a POST. In this case the values would be available to the third page in GET:
$_GET['key']
If you use session, the values stay server-side. So in the second page you can set the value:
$_SESSION['key'] = $value;
And then retrieve it in the third page:
$value = $_SESSION['key'];
Note that these session values will continue to live on the server until the session times out. You may want to unset them from the session once you're done with them if it starts to add confusion to other pages the user visits which also make use of these values.
Page 1
<?php
// this starts the session
session_start();
// this sets variables in the session
$_SESSION['color']='red';
$_SESSION['size']='small';
$_SESSION['shape']='round';
?>
Page 2
<?php
$color = $_SESSION['color'];
$size = $_SESSION['size'];
$shape = $_SESSION['shape'];
?>
and so on...

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

How to retrieve the checked state of a checkbox from a Html form and store it in a database?

i have a form field
<input type="checkbox" name="page" value=""/>
and corresponding field in mysql db is true and false, if someone click the checkbox i would like to send TRUE value to db via POST, how do i achieve it ?
You give the input any value you like:
<input type="checkbox" name="page" value="true"/>
Then, if the checkbox is checked, it will be a successful control and submitted.
<?php
if (isset($_POST['page']) && $_POST['page'] == 'true') {
// Then insert something into the database as normal
}
?>
If you want to set it when the checkbox is not ticked, then you will need an else to go with the if.
For a checkbox, the value attribute determines what the value will be if the item is checked. If it isn't checked, then no value will be submitted at all. You should therefore always specify the value attribute on a checkbox.
If you want the checkbox to default to checked, then you also need to specify the checked attribute.
<input type="checkbox" name="page" value="1" checked='checked' />
The Form:
<form action="/path/to/processing_script.php" method="POST">
<!--... Other Form Elements go here -->
<input type="text" name="color" />
<input type="checkbox" name="page" value="True"/>
<input type="submit" value="Send to Database" />
</form>
Processing script:
(processing_script.php)
<?php
// Check is 'True'?
if ($_POST['page'] != 'True')
{
$_POST['page'] = 'False';
}
$con=mysqli_connect("your-db-loc","your-db-username","your-db-pass","db-name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL Database: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO TableNameHere (True-false, Favorite Color)
VALUES ($_POST['page'], $_POST['color'])");
mysqli_close($con);
?>
This example I created add's 2 data types to a new row on the database.
Replace the text 'TableNameHere' with your db table name, should be in similar format to: 'prefix_colors_tble'
Replace the text "your-db-loc" with your databases location, usually 'localhost' for internal server, or could be a URL for live server.
Replace the text "your-db-username" the username used to login to mysql, must have sufficient privileges.
Replace the text "your-db-pass" the user's password
Replace the text "db-name" database name (not deemed important unless containing multiple databases)
Replace the text "True-false" & "Favourite Color" with your db table column headings as appropriate.
Good Luck! -p.s. I know this answer is a few years late, but I hope it can help somebody else. Send your appreciation to http://amazewebs.com/testimonial Thanks.
Collect the follows by reading $_POST after form submission, then write them to the database using mysql_query
the first thing you will have to do is to modify the current html code for checkbox and add something in the value field.
let say you set the value to 1.
The second thing is if you are posting the form, then you will have to process the form using a server side language like PHP,Perl, Java etc.
for e.g. in PHP you can get the catch what is sent for the page field using $_POST['page'].
Now you will have to do a bit of server side processing to see if the $_POST['page'] == '1' , then set $page = 'true';else set$page = 'false';
the you can insert the $page into the database by using the library functions of the language you are using.

implement a button to send information to another php file?

I've got the following php code printing out the contents of a SQL table.
$query="select * from TABLE";
$rt=mysql_query($query);
echo mysql_error();
mysql_close();
?>
<i>Name, Message, Type, Lat, Lng, File </i><br/><br/>
<?php
while($nt=mysql_fetch_array($rt)){
if($nt[name] != null){
echo "$nt[id] $nt[name] $nt[message] $nt[type] $nt[lat] $nt[lng] $nt[file]";
}
}
?>
How would I implement a button so for each "row" if the button is clicked on that row it'll submit the information of that row to another php file?
I want it looking something like...
details details2 details3 BUTTON
details4 details5 details6 BUTTON
details7 details8 details9 BUTTON
details10 details11 details12 BUTTON
Where if BUTTON was hit on row 1 details1,2,3 would be sent to a php file, on row 2 detals 4,5,6 would be sent etc. How would I do this?
Thanks.
it's going to be something like that, depending on the data you need to send:
while($nt = mysql_fetch_array($rt)) {
if($nt[name] != null){
echo "$nt[id] $nt[name] $nt[message] $nt[type] $nt[lat] $nt[lng] $nt[file] ".'send request<br/>';
}
}
You can either use GET method and send a query string to the second php page and receive the variables there, like
next.php?variable1=value1&variable2=value2&...
or use POST method by making a hidden form for each row and assign a hidden field for each variable you want to send.
<form method="post" action"next.php">
<input type="hidden" name="variable1" value="value1" />
<input type="hidden" name="variable2" value="value2" />
.
.
.
</form>
or instead of sending all the values, just send the row ID (if any) using any of these two methods and run another query in next.php to get the information you need from database.
Instead of submitting the entire data, just send the ID and fetch the results from the database in the other script. If you want to have an input button, you can do
<form action="/other-script.php" method="GET">
<?php printf('<input type="submit" name="id" value="%s" />', $nt["id"]); ?>
</form>
but you could also just add a link, e.g.
printf('Submit ID', $nt["id"]);
If you really want to send the entire row values over again, you have to make them into form inputs. In that case, I'd send them via POST though.

Categories