How to parse all data from 1 table to another page? - php

I have printed the table get from database like below
And my code
print "<form id='form1' name='form1' method='post' action='http://localhost/live/index.php?m=sync&a=update'>";
while($db_field = mysql_fetch_assoc($result))
{
print "<table border=1 width=100%>";
print "<tr><td width=5%><input name='taskid' type='text' value=".$db_field['task_id']." readonly=readonly></td>";
/*print "<td width=10%>".$db_field['task_name']."</td>";*/
print "<td width=5%><input name='percent' type='text' value=".$db_field['task_percent_complete']." readonly=readonly></td>";
print "</table>";
}
print "<input name='Sync' type='submit' value='Sync' id='Sync' />";
print "</form>";
mysql_close($db_handle); /*.$db_handle */ /*<---to check the resource link and id*/
}
else{
print"Failed" ;//.$db_handle;
So what i want to know how to parsing all the datas from the database to another page like the action i want to send, because now i just can parsing 1 data in 1 table when i click the sync button like below is my parsing code in another page
The image below is the parsing code
I have no idea how to display all the data in new page...it is need to use loop? im newbie, big thanks

Edit based on comments below:
For starters, in the first code, move the print "<table border=1 width=100%>"; and print "</table>"; parts outside the while loop because the table is getting generated twice as two separate tables.
What's happening with the current code is that the second pair of fields taskid and percent are overwriting the first because the names are the same, so you only see the second pair of values in your screenshot. You need to make the input field names an array: put square brackets [] in the name so that taskid and percent are automatically arrays in $_POST. This is what the HTML source should look like in the form:
<input name='taskid[]' type='text' ...>
<input name='percent[]' type='text' ...>
(Or manually subscript them like taskid_0, percent_0 and taskid_1, percent_1; but then you have to decide when to stop looping or use variable variables.)
After that, in the target page where you are processing $_POST["taskid"], it will be an array which you can access as $_POST["taskid"][0], $_POST["percent"][0] and $_POST["taskid"][1], $_POST["percent"][1]. So loop through that when updating the database and generating your 2nd html:
print_r($_POST["taskid"]); // verify that this is an array
print_r($_POST["percent"]); // also an array
$i=0;
foreach ($_POST["taskid"] as $t) {
// not using $t, that's just for looping convenience
// do sql insert/update here, i'm just showing how you'd loop the array
print "<td><input type='text' name='".$_POST["taskid"][$i]."' readonly=readonly></td>";
print "<td><input type='text' name='".$_POST["percent"][$i]."' readonly=readonly></td>";
$i++;
}
Hope that helps.
Some pointers: 1. Don't put images of your code, just paste the code. 2. The generated HTML copy-pasted (browser -> view source) is more useful than an image of the page.
version 1:
1. If I understand it correctly, you want to show the form on one page and when the user clicks Sync (sumbit) you want it to go to another page which will process the form?
Use the target attribute of the <form> element (link). Like:
<form action="form_action.php" method="post">
Or,
2. If you want to process the form first (same page) and send the user to another page:
send an HTTP 302 re-direct + Location header.
You can also set the redirect in your HTML after processing the page using:
<meta http-equiv="Refresh" content="0; url=http://www.example.com/" />

Related

How to separate checkbox variable results outputted in a while loop in PHP?

I'm trying to write an attendance system that, when a user is present at a class, the staff will check a box and the program will then add one to the present count of the relevant customers. The problem is to output the register, taken from phpMyAdmin, it uses a while loop so all the checkboxes have the same variable name. This is the code I have so far...
echo "<form 'action=badminreg.inc.php' method='post'>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row['bookingID']."</td><td>".$row['firstName']."</td><td>".$row['surname']."</td><td><input type='checkbox' name='present' value='present'</td><td><input type='checkbox' name='incident' value='incident'</td></tr>";
}
echo "<input type='submit' name='reg-submit'>";
echo "</form>";
isset($_POST['reg-submit']);
$pres = $_POST['present'];
I need to separate the check box inputs so that the program will be able to mark individual users differently to others. I'm sort of new to PHP as this is for my A-level coursework so is there a way to get around this? Any help would be great. Thanks
You can define the name for the checkbox elements as array and pass the bookingID as value.
Example (untested):
$output = "<tr><td>{$row['bookingID']}</td><td>{$row['firstName']}</td><td>{$row['surname']}</td><td><input type='checkbox' name='present[]' value='{$row['bookingID']}'</td><td><input type='checkbox' name='incident[]' value='{$row['bookingID']}'</td></tr>";
The variables $_POST['present'] and $_POST['incident'] contains then an array with the IDs of the selected check boxes.
If you change it to name='present[]' then when you submit the data again, you'll get an array of values inside $_POST["present"] instead of a single one. (You'll get one item in the array for each checkbox with that name which was actually checked - a quirk of HTML forms is that if the checkbox wasn't checked, its value is not submitted at all).
You'll also want to change the value of the checkbox to be the ID of the customer (or booking, maybe), so you can identify which box was checked.
Same for the "incident" checkbox as well, of course.
So you're aiming for something like this, I think:
echo "<tr>
<td>".$row['bookingID']."</td>
<td>".$row['firstName']."</td>
<td>".$row['surname']."</td>
<td><input type='checkbox' name='present[]' value='".$row['bookingID']."'</td>
<td><input type='checkbox' name='incident[]' value='".$row['bookingID']."'</td>
</tr>";

How to access checkboxes with unknown names in PHP

I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.

How to pass data of many textbox values with POST array in PHP

I have this form that contains dynamically generated textboxes filled with values (those are read from the database), and I let the user modify and save them.
But I don't know how to save the data, how to pass them to the "saver" php page (which eventually the same now, doesn't matter...)
For now, they seem like this:
echo "<td><input type=\"text\" id=\"category$category_id\" name=\"category$category_id\" value=\"$category_sequence\" style=\"width: 25px;\" /></td>";
What should be the "name" in this side, and how to reach them from the $_POST on the other side?
In PHP, take a look what you have from your form so far:
<?php
print_r($_POST);
?>
This code will show you what you have. Then you can access any field by its name:
<?php
$variable = $_POST['field_name'];
?>
Be sure to check if there is any POST data was sent:
<?php
if (isset($_POST) && is_array($_POST))
{
// ...
}
?>
Be sure that you have needed field sent by POST form:
<?php
$variable = (array_key_exists('field_name', $_POST) ? $_POST['field_name'] : '');
?>
Finally I got results.
I should use this way:
print "<input type="text" name="cat[]" value="$category_sequence" />"
Then an array ($_POST['cat']) will be created I can iterate through.
Or:
print "<input type="text" name="cat[$catId]" value="$category_sequence" />"
Again, iteration.
On the server side, if I stay on my original idea:
$i=1;
while(isset($_POST['cat'.$i]))
{
print "There is "cat".$i item, it is processable."
$i++;
}
All I wanted was this... thank you.

Input from PHP generated form is not being recorded

The issue I have been experiencing deals with input from HTML which was generated using PHP echo statements. Here is the function I have that outputs the form:
function confirm_recipients()
{
echo "<form action = ' ' name ='email_options' method='post'>";
echo "<input type='submit' name='sendRecipients' value='Yes, I want to send the emails' >";
echo "</form>";
}
Later on in the same PHP page, I call the function and then check to see if the submit button was set.
confirm_recipients();
if (isset($_POST['sendRecipients']))
{
//perform actions
}
However, this code is not functional seeing as even when the submit button is set (clicked by the user), the if statement block is never executed. Perhaps there is an issue with posting from the same file I want to "read in" from? Thanks for any advice.
Updates
Thank you for such immediate response. Sadly none of the suggestions have worked (removing the space in the action value or the suggestion made by user623952). No errors have been reported, the button is just failing to be set. I am looking for other places in the file that might have errors, perhaps in the order I call the function.
This works fine for me:
<?php
print "<pre>".print_r($_POST,true)."</pre>";
confirm_recipients();
function confirm_recipients() {
echo "<form action = ' ' name ='email_options' method='post'>";
echo "<input type='submit' name='sendRecipients' value='Yes, I want to send the emails' >";
echo "</form>";
}
if (isset($_POST['sendRecipients']))
{
print "<br/>sendRecipients is set!<br/>";
}
?>
I think your problem might be somewhere else in the code.
It's okay to POST the form data to the same script that contains the form. Change the action attribute to the URL of the script, do not set it to whitespace, which is what you did.
I don't think the value of a submit input is sent as part of the POST. Try using an input type="hidden" with the name 'sendRecipients'.

HTML Numerical Input Bug: infinite loop when jquery.change event called

I created an HTML table with PHP as follows:
$i = 1;
while($row = mysql_fetch_array($result)){
Print "<tr>";
Print "<td><input id='prEff[$i]' type='number' step='0.01' min='0.01' max='0.99' value='.85' </td>";
Print "<td>".$row['ErdEfficiency'] . "</td>";
Print "<td>".$row['TheoreticalSEC'] . "</td></tr>";
$i++;
}
The input cell has a jquery.change function that is called when the number is changed within the range. During debugging, clicking the up or down button once (in chrome) causes the input to run through all values until the upper or lower limit is reached. So the function is called, but only after the whole range of values is run through.
If the page is refreshed without debugging, the jquery is called, but the button sticks since it is experiencing the bug as described.
Here is the simple jquery function:
$('[id^="prEff["]').change(function (){
var test = this;
alert("hi");
});
Its been a difficult bug to track, and I'm not sure what is causing it. It has occurred with an onchange attribute in the input, as well as a javascript eventListener, and jquery change. It may be the way the PHP is printing the input but I've tried a couple different ways without success.
It seems like you have an unclosed <input> tag in your code. Make sure you close it and you should be fine:
Print "<td><input id='prEff[$i]' type='number' step='0.01' min='0.01' max='0.99' value='.85' /> </td>";

Categories