Passing form information in a for-loop - php

Maybe this is a stupid question, but I was wondering if I could get information passed with a form into a for-loop.
The problem is as follows:
The passing of the information works, though he passes only for the last loop. For example if I click the submit button for loop 2 ($i = 2). The command $_POST['titel'] will only remember the information in last loop ($i = $numact-1) and not loop 2 ($i = 2).
for example if titel[0] = test0, titel[1] = test1, titel[2] = test2. and I click the submit button below titel[0] he passes the information from titel[2]. Is there an easy way to get around this?
I have the following code (For the sake of simplicity I shortened it);
<?php
for ($i = 0; $i <= $numact-1; $i++) {
echo "<tr><td width='150'>
<input type='text' name='titel' value='$titel[$i]' />
</td></tr>
<tr><td><input type='submit' name='submitreg' value='Toon activiteit'/>
</td></tr>";
}
?>

You're using the same parameter name over and over again (name=titel - you had a type and probably meant to write as 'title') so when the form submits - only one value will be passed.
You can easily fix that by passing the parameters as:
...
echo "<tr><td width='150'>
<input type='text' name='titel$i' value='$titel[$i]' />
</td></tr>
<tr><td><input type='submit' name='submitreg' value='Toon activiteit'/>
</td></tr>";
...
and reading it on the other side as title0, title1 etc.

As seen in this post, you can pass in an array simply by putting brackets around the index. PHP will reconstruct the array for you.
Also, you probably want your submit at the end of your table, not after each row. Your code should look something like this:
<?php
for ($i = 0; $i <= $numact-1; $i++) {
echo "<tr><td width='150'>
<input type='text' name='titel['.$i.']' value='$titel[$i]' />
</td></tr><tr><td><input type='submit' name='submitreg' value='Toon activiteit'/>
</td></tr>";
}
?>
The advantage of this approach is that it's more extensible, should you choose to use different values. However, Edson Junior's approach is slightly simpler.

You can change the name attribute to name=titel[] so PHP will automatically transform it to an array. It is not necessary to specify the index inside title[].
For example:
<input type="text" name="titel[]" value="x" />
<input type="text" name="titel[]" value="y" />
<input type="text" name="titel[]" value="z" />
When you submit the form, PHP will transform it to
"title" = array (
0 => "x",
1 => "y",
2 => "z"
);
In case you need to check what button was clicked, you could change the inputs type="submit" to <input type="button" name="submitreg" class="submitreg" id="whatever_you_want_but_has_to_be_unique" />.
Outside the loop, add another input wich will have the value of what button was pressed.
<input type="hidden" id="buttonPressed" name="buttonPressed" value="" />
Then add this code (you need to import jQuery library to the page so it understands the code below, wich is jQuery, here is the Docs.
<script type="text/javascript">
$(function(){
$("button.submitreg").live("click", function(){
var buttonPressed = $(this).attr("id");
("input#buttonPressed").val(buttonPressed);
});
}
</script>
All you need to do is get the buttonPressed value and you'll know what button was pressed.

Related

How can I display a variable number of items using radio buttons in HTML?

file.json: {"items":[{"num":1,"color":"red"},{"num":2,"color":"blue"}]}
Objective: Read file.json using PHP and delete the objects from the array and save.
Method: I am reading the file and displaying the array items alongside radio buttons. Objects corresponding to the selected radio button are deleted.
Code:
<?php
$myfile = fopen("/home/user/php/".$filename,"r" ) or die("unable to open file");
$myjsonstr = fread($myfile, filesize("/home/user/php/".$filename));
fclose($myfile);
$jsons = json_decode($myjsonstr, true);
?>
<form action="delete.php" method="POST">
<input type="radio" name="testcase" value="1"> <?php print_r($jsons["testcases"][0]);?>
<input type="radio" name="testcase" value="2"> <?php print_r($jsons["testcases"][1]);?>
<input type="submit" name="delete" value="Delete Selected Values" />
</form>
Problem: I need to make my list dynamic in length because the value field of "items" can have variable number of objects. But it seems like number of radio buttons in HTML cannot be variable. As you can see from the code snippet, The no. of radio buttons is always 2. I'll have to change the code if the array in my JSON had 3 objects instead of 2.
Is it possible? How?
Thanks, prime_mover! That additional detail helps. Let's assume the part down to the json_decode is right, and you've got a decoded object in the variable $jsons.
Let's put the test cases in their own variable for brevity as well.
<?php
$testCases = $jsons["testcases"]; // array of indeterminate length
?>
<form action="delete.php" method="POST">
<?php
foreach ($testCases as $ix => $caseTxt) {
$v = $ix+1;
?>
<input type="checkbox" name="testcase" value="<?=$v;?>" /><?php print_r($caseTxt); echo "<br>"; ?><br>
<?php } ?>
<input type="submit" name="delete" value="Delete Selected Values" />
</form>
The loop writes one new input for each entry in the $testCases array.
Not saying this is perfect code, or that it does exactly what you want to do, but it does handle a list of unknown length.
You would probably want to handle a zero length differently.
Notice I changed the type to checkbox, because your text below said "Delete Selected Values" so I guess you want to allow more than one to be selected.

Returning only the last value of query

This is my second code but the problem is I have 3 queries. So it only returns the last product_id when i Click update it always return product_id=3, but i want update the product_id=2
<form action="update_qty.php" method="POST">
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
<?php } ?>
</form>
Your problem is that the PHP is server side and you need something client side to read the value of the text box. You would need a page refresh to pass the text field value to the server so it could write it to the url in the anchor tag. Which is what the form submit would do, but as it would have submitted the value already the anchor tag would be pointless
To do it without a page refresh use Javascript. It would be easy to do with jQuery. You could add an event that writes whatever is entered in the text box the the anchor tags href as it is typed.
I'll do something more like this.
One form per product.In your case when you submit the form the qty value will always be the las found.
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<form action="update_qty.php" method="POST">
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
</form>
<?php } ?>
You can add more information like this
update
You can not get all values as like that because input name overwrite in every loop iteration.
For multiple values you can try in two ways like:
<?php
while($getorder = mysqli_fetch_array($order)){
$newArr[] = $getorder['price']."~".$getorder['product_id']."~". $ getorder['qty'];
} //while end
?>
<input type="hidden" name="allinputs" value="<?=$newArr?>">
Input field outside the loop.
In php explode array value with ~ and get the all values.
Other solution is that
Your input field name must be change like:
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price_<?=$getorder['product_id']?>">
<?php } ?>
Change field name in every iteration.
In current scenario either you need three different buttons or the best solution to use AJAX request .
update
On update_qty.php u can use like this
<?php echo $_GET['product_id'];?>

Submit button in loop

I am having a problem using submit button in loop.
What I am trying to do is to show a list from a table in a database and next to each row a submit button.
That insert into a table the id of that row my code is
for ($i = 0; $i <= count($all_rows)-1; $i++) {
<form>
<input type='text' id='name' value='".$all_tv_shows[$i]['id']."' />
<input type='button' value='Submit' onclick='addRecord()' />
</form>}
I am using AJAX with the submit buttons.
so when i press on any submit button the value that inserted in the table is all the same value (the last row that showed)
Try this, close the php tags properly
<?php for ($i = 0; $i <= count($all_rows)-1; $i++) { ?>
<form>
<input type='text' id='name' value='".$all_tv_shows[$i]['id']."' />
<input type='button' value='Submit' onclick='addRecord()' />
</form>
<php } ?>
You need to close the PHP tags:
<?php
//assuming some other code first...
for ($i = 0; $i < count($all_rows); $i++) {
?>
<form>
<input type='text' id='name' value='<? php echo$all_tv_shows[$i]['id'];?>' />
<input type='button' value='Submit' onclick='addRecord()' />
</form>
<?php
}
Also, it's not hugely important, but it might be easier to read if you change the for loop as above.
I guess the problem is not in the code you have shown, the problem should be in addRecord javascript function on top of that id is same i.e. 'name' for all element....
You get the value from the form using $('#name').val(); or document.getElementById('name'); and look all input has same id. If I am going right then pass value in addRecord function and use that value.

Passing multidimensional array data to PHP page taking values from dynamically created textboex

I need help regarding how to collect data from text boxes created dynamically. I am giving my html code. my adding and removing code for textboxes is working prefectly. I would like to know where i am doing wrong whether in defining array of textboexs. Whether i am not collecting textbox values properly. Another question is how should i pass this array value to another page after submitting page for inserting into DB.
This code is for taking values for itineraries for a tour for travel agent.
Here is my html form
`
Enter Itinerary Details
Name of Tour (category)
Days
City
Itinerary
Night Stay
-->
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<label></label>
<input type='text' id='dayNo' name="itinerary[]" >
<input type="text" id='cityName' name="itinerary[]">
<input type='text' id='schedule' name="itinerary[]">
<input type='text' id='nightStay' name="itinerary[]">
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
<input type="submit" name="submit" id="submit" value="Submit" />
</td>
</tr>
</table>
</form>`
I would like to know does i have defined correct array name "itinerary[]".
If there are 10 days tour then there will be 10 rows containing 4 fields. How should i collect those rows and send to another page for inserting. Please let me how should i write the VALUES () section after collecting into array. Can i send this data of 10 rows using session. Can i send this data as parameter. I am sorry for so many questions in one post. I have tried all these way but no successes or most probably i m wrong somewhere
Please help me this is live site. Stuckedup in this part
Thanks millions in advance.
Sorry for this delayed reply to your ans. Actually i really getting no idea about how should i declear the arrays. Honestly this is mking me very frustrating. and loosing my time. Please Guide me if u can.
I am giving my JS code for adding the text box dynamically and in my previous post i have given the HTML code. Can u check please whether i am doing correct the naming convention for the declearing array. Please make necessary changes into my code please and paste here plz.
Here is my JS code adding textboxes dynamically
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>30){
alert("Only 30 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter + ' ' + 'style="width:750px;"');
newTextBoxDiv.html(
'<input type="text" name="itinerary[dayNo]'+ counter + '" id="dayNo'+ counter + '" value="'+ counter + '" >' +
'<input type="text" name="itinerary[cityName]'+ counter + '" id="cityName'+ counter + '" value="" >'+
'<input type="text" name="itinerary[schedule]'+ counter + '" id="schedule'+ counter + '" value="" >'+
'<input type="text" name="itinerary[nightStay]'+ counter + '" id="nightStay'+ counter + '" value="" >' );
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
No i am giving again my HTML code.. can you check whether i am giving the names properly or not.. It will be greatest help for me.
Here is my HTML Code
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label></label>
<input type='text' id='dayNo' name="itinerary[dayNo][]" >
<input type="text" id='cityName' name="itinerary[cityName][]">
<input type='text' id='schedule' name="itinerary[schedule][]">
<input type='text' id='nightStay' name="itinerary[nightStay][]">
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
<input type="submit" name="submit" id="submit" value="Submit" />
Now tell me how should i pass the values collected in the array to either session or thru URL like ---action="savedata.php?arr=...."
Please make correction in my code itself.. i m new and feeling very lost since last few days.
I wrote like this about passing the values to array
<?php
$totalArray = itinerary;
$_session['tArray'][]=$totalArray;
?>
Is this correct way to send thru session.
Thanks millions
in advance
I'm not sure to understand your issue very well, i'll try to explain steps.
Don't use generic ID for dynamics inputs.
PHP doesn't matter about id's
If you want to match a "block" of schedule, and match it with jQuery, set a proper data-* to each, or even a class.
Here's an example :
<div class="TextBox" data-formNum="0">
<input type='text' name="itinerary[dayNo][]">
<input type='text' name="itinerary[cityName][]">
<input type='text' name="itinerary[schedule][]">
<input type='text' name="itinerary[nightStay][]">
</div>
When you want to add a block of form with jQuery, use :
var idToAdd = $(".TextBox:last").attr("data-formNum")+1;
When you send this form to PHP, everything is going to be formated like :
Array
(
[intinerary] => Array
(
[dayNo] => Array
(
[0] => 15
[1] => 14
)
[cityName] => Array
(
[0] => London
[1] => Prague
)
...
Then you can write an INSERT INTO function cycling on this array like:
for ($i=0; $i < count($_POST['itinerary']['dayNo']);$i++)
{
$day = $_POST['itinerary']['dayNo'][$i];
$cit = $_POST['itinerary']['cityName'][$i];
}
Hope this helped.
Let me know if I misunderstood.

How to do + or - in php?

I want to have a form in following way:
[-] [value] [+]
I don't know how to script the logic to get the value 1 higher or 1 lower in PHP.
I assumed something like following would work:
<?php
$i = 0;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['plus']))
{
$i++;
}
if(isset($_POST['min']))
{
$i--;
}
}
?>
and my form is as following:
<form action="" method="post">
<input type="submit" name="min" value="-"> <input type="text" value=<?php echo $i ?> > <input type="submit" name="plus" value="+">
</form>
But I'm only getting either a 1 or a -1. Can someone show me how to do this in a good way?
Try this:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$i = $_POST['current_value'] || 1;
if(isset($_POST['plus']))
{
$i++;
}
if(isset($_POST['min']))
{
$i--;
}
}
?>
and this:
<form action="" method="post">
<input type="submit" name="min" value="-"> <input name="current_value" type="text" value=<?php echo $i ?> > <input type="submit" name="plus" value="+">
</form>
You need some way to get the current value to persist between requests - depending on your use case, you may need database storage as Rocket mentions, or this simple passing back of the current value may be enough.
PHP will simply load code on the server-side and run when the page is loaded. If you are looking to dynamically increment/decrement the value while remaining on the same page, I suggest you look into learning Javascript and jQuery.
Reference: https://developer.mozilla.org/en/JavaScript/
Reference: http://jQuery.com/
What is happening with your code is that you are incrementing a global variable that you set to 0 in the beginning. That is why the only values you get back or 1 or -1. This can be fixed by passing the variable you increment each time instead of using a global variable. That way it keeps the value between each plus and minus and doesn't keep resetting it.

Categories