implement a button to send information to another php file? - php

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.

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 Access $_POST Data Across Multiple Forms

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'.

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);
}
}

check if checkbox is checked in php

I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>

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.

Categories