$_POST superglobal in foreach loop not working - php

With below code I select a quantity, then I check the Item whose quantity I have selected then I click the add button to submit the form.
<form name="addtocart" method="post" action="checkbox.php">
//foreach loop below loops through array of items fetched from the db
<?php foreach($result2 as $row) { ?>
<select name="qty">
<?php for ($i=0; $i < $row['prd_quantity'] + 1 ; $i++) { ?>
<option value = "<?php echo $i; ?>" ><?php echo $i; ?></option>;
<?php }?>
</select>
<input type="checkbox" name="checkitem[]" id="addtocart" value="<?php echo $row['prd_id'] ?>" optional /></p>
<?php } ?>
enter code here
<input type="submit" value="Make Order"/>
</form>
After selecting, say 8 on the select element, $ordqty below still outputs 0. I am thinking its something to do with the loop and $_POST superglobal but
checkitems[ ]
works. Help would be appreciated. Thanks.
$ordqty = $_POST['qty'];
//$ordqty returns 0.
Below is the HTML Generated for the first item whose $row['prd_quantity'] = 8 :
<select name = "qty">
<option value="0">0</option>
;
<option value="1">1</option>
;
<option value="2">2</option>
;
<option value="3">3</option>
;
<option value="4">4</option>
;
<option value="5">5</option>
;
<option value="6">6</option>
;
<option value="7">7</option>
;
<option value="8">8</option>
;
</select>

Seems to me like if there's more than a single row returned by your DB then there will be multiple select elements within your response, all named qty. This could explain why the form isn't posting the correct value. Have you checked that?
Try something along the lines of:
<select name="qty[<?php echo $row['prd_id']; ?>]">
<?php for ($i=0; $i < $row['prd_quantity'] + 1 ; $i++) { ?>
<option value = "<?php echo $i; ?>" ><?php echo $i; ?></option>;
<?php }?>
</select>
This will post an array of selections keyed by product IDs.
Update
Thank you for the idea of indexing the array of selected items' quantities using product IDs worked.
And to access the elements of the qty[ ] array , I know this could be better, but I did:
//Array below holds the values of the quantities entered
$new_ord_qty = $_POST['qty'];
//Array below holds product ids -- in the HTML code -- prodid is the name of a hidden inputfield inside the foreach loop whose value i have set to $row['prd_id']
$prod_id_array = $_POST['prodid'];
for($i=0; $i<count($checked_items_array);$i++) {
for ($i=0; $i < count($new_ord_qty); $i++) {
//Array below holds the values of the quantities entered with the prod_id_array elements as //the indices
$ord_qty = $new_ord_qty[$prod_id_array[$i]];
// Here echo will output an array of the quantities entered for the checked items
echo $ord_qty;
}
}
Thanks folks.

I think the issue might be that you are passing the checkbox as an array checkitems[] but you are passing the quantity as a single qty might be worth changing the name of the quantity select to qty[]
Obviously you may also need to update your code to handle the qty being an array and match it to the checkitem value.

The problem should be that you have multiple selects with the same name, I assume that the POST variable will show the last one, which is still set to 0. You might use an id postfix, like, qty_0, qty_1 for each dropdown list.
Could you post the HTML code the segment generates? That might helpful.

Related

How can i create an even number of groups with an od number of elements USING PHP

The goal of this program is to form a number n_group of groups with a number n names per group.
This is the code prototype that i am using to solve the problem:
first i start a session:
<?php
session_start();
?>
created a form so the user can isert the names so i can create the groups later
`<form method="post" action="index.php" class="input1">
<div>
<input type="text" name="name_in" id="name_in" placeholder="Inserisci il nome" autocomplete="off" />
<button type="submit">Invia</button>
</div>
</form>
created a selection menu so the user could select the number of groups
`<form method="post" action="index.php" class="input2">
<div>
<label for="nog">Seleziona il numreo di gruppi</label>
<select name="nog" id="nog">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<button type="submit">Invia</button>
</div>
</form>
HERE I START THE FORST PART OF THE PROBLEM WHITCH IS TO DISPLAY THE NAME AS AN ORDERED LIST SO I DID THIS
first i controllel if the session was already set and if not i assigned it as an array:
`if (!isset($_SESSION["list"])) {
$_SESSION["list"] = [];
}
if the user submitted data and the data was set i pushed it into the session array:
`if ($_POST and isset($_POST["name_in"])) {
array_push($_SESSION["list"], $_POST["name_in"]);
}
i shuffled the array since the grouping hould be casual:
`shuffle($_SESSION["list"]);
finally i displayed it as an ordered list:
`echo "<ol>";
for ($i = 0; $i < count($_SESSION["list"]); $i++) {
echo "<li>" . $_SESSION["list"][$i] . "</li>";
}
echo "</ol>";
THEN I STARTED THE SECOND PART: DIVIDING THE NAMES IN GROUPS
first i check i ìf the user submits the number of groups, if not i set the n_group variable to the value 1
`if (isset($_POST["nog"])) {
$n_group = $_POST["nog"];
} else {
$n_group = 1;
}
i need three variables to cycle freely in the variable
starting counter: indicates the startin point which varies based on the group that we are considering
end counter: it works just like the starting counter
member varible: corrispond to the minimum number of members per group (total number of members / number of goups) the result of the operation is given as an integer for obvious reasons
`$counter_start = 0;
$counter_end = intdiv(count($_SESSION["list"]), $n_group);
$member = intdiv(count($_SESSION["list"]), $n_group);
if the total number of members and the number of groups are multiples of each other the problem is simpe to solve by using this code
`if ((count($_SESSION["list"]) % $n_group) == 0) {
for ($i = 0; $i < $n_group; $i++) {
echo "<ol>";
for ($j = $counter_start; $j < $counter_end; $j++) {
echo "<li>" . $_SESSION["list"][$j] . "</li>";
}
echo "</ol><br>";
$counter_start += $member;
$counter_end += $member;
}
}
the problem is that i cant find a way to solve the grouping problem if the total number of members and the number of groups are not multiples(eg. 19 names divided in 4 groups)
how can i solve the problem?

PHP concatenation $i in jQuery

Bit of a strange one, I have a webpage that iterates through a set number of times using while ($i <= 21):. During this iteration I have a dropdown in each which displays some values I pulled from a database, at this point that specific value doesn't matter but the id of each dropdown uses the value of $i. For example:
<select name="dropdown<?php echo $i; ?>" id="dropdown<?php echo $i; ?>">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
What I am then wanting to do is take the value selected from that dropdown and place in another field that also has the id corresponding to the iteration number, for example:
<textarea name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>"></textarea>
I am using the following code for the jQuery to get the value from the dropdown and put it into the textarea:
<script>
$("#dropdown<?php echo $i ?>").on("change",function(){
//Getting Value
var selValue = $("#dropdown<?php echo $i ?>").val();
//Setting Value
$("#textfield<?php echo $i ?>").val(selValue);
});
</script>
However it doesnt seem to like the use of <?php echo $i ?> part as if i replace that with for example 2 or 3 then it works for that iteration.
I have tried setting the variable in PHP like: $textfield= 'textfield'.$i; and the using this as a whole in jQuery like this: $("#<?php echo $textfield ?>").val(selValue); but it doesnt like that either. Interstining if I change it to $textfield= 'textfield'.'2'; or $textfield= 'textfield2'; it works. Seems like it doesnt like my use of $i, is it the PHP concatenation that it doesnt like?
Anyone experienced this or know of a fix?
Huge fixes are required in your code but will explain the solution in minimal coding.
use array in name,dont use id,use class and data attribute to store the loop value as follows
<select name="dropdown[]" class="dropdown" data-id="<?php echo $i; ?>">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<textarea name="textfield[]" class="textfield<?php echo $i; ?>"></textarea>
now in script single piece of code is enough to perform your operation with the help of class dropdown and dynamic class textfield
<script>
$(".dropdown").on("change",function(){
//Getting Value
var selValue = $(this).val();
var dynamic_id = $(this).data('id');
//Setting Value
$(".textfield"+dynamic_id).val(selValue);
});
</script>

When i select value form dropdwon is does not show in php $_Post['name']?

First of all, I am working on editing mode. I Fetch data from database then match it form selected item from last time.
when I change the value of dropdown it does not change it returns me the blank value in $_POST[]
I am populating a Drop Down Box using the following code.
<select name="agency_name" class="form-control">
<option value="">--Select--</option>
<?php
$query_agency= "Select * From `agency_name`";
$count = $db_handle->numRows($query_agency);
if($count != 0){
$i = 0;
$result_agency = $db_handle->runQuery($query_agency);
while($i != $count){
$agencyname = $result_agency[$i]['name'];
?>
<option value="<?php echo $result[0]['Agency_name'] ?>"
<?php if($result[0]['Agency_name']=="$agencyname"){echo "selected";} ?>>
<?php echo $agencyname;?>
</option>
<?php
$i++;
}
}
?>
</select>
I want to show change value and store in the database. Now how can I get the selected option value using PHP because I want the selected value to perform a query in the database.

How can I create a Dropdown Box for quantity where min. is 1 and max is set by a variable? (PHP)

was wondering if anyone had any idea if this was possible.
For an e-commerce site, there is a variable for max quantity allowed, let's just say its $maxqty.
On the checkout page, we have an input box for quantity. We want to change this to a dropdown box, but each item has a different limit ($maxqty).
Is there a way to create a dropdown box with a minimum value of 1 and a maximum value of $maxqty.
Specific Example:
Item #1, Max Qty = 5
Item #1 at Checkout Box, Quantity Drop Down would show choices for 1,2,3,4,5
Thanks for reading!
select tags in html are used to create dropdown list, which on checkout/submission of form, will give you the selected value in php.
Example:
<select>
<?php
for($i=1;$i<=5;$i++) {
echo "<option value='$i'>$i</option>";
} ?>
</select>
should be easy, you can place max qty in a variable , and then loop from 1 to that max qty, creating an option each time like e.g.
<? php
for($i=1;$i<=$item_max;$i++)
{
?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
Assuming you are getting the max from querystring. It could also be assigned by other ways
<?php
$maxQty = (int) $_GET['max_qty'];
?>
<select name="quantity">
<?php
for($i=1; $i<=$maxQty; $i++)
echo "<option value='$i'>$i</option>";
?>
</select>
OUTPUT
<select name="quantity">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
This really depends a lot on your setup, that is how your form elements are generated.
You can just generate the select options through a for loop
<select name="quantity>
<?php for($i=1;$i<=$maxqty;$i++) {?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<? } ?>
</select>
Note that this intermixing of php in your html code is generally ill-advised and should be preferably separated

Using PHP $_POST to remember a option in a select box?

I have a form which POSTs to itselft so the user can do things that you would find in a Shopping Cart.
e.g. Increase quantity, select postage type.
My problem is for my form Select element called "postage" whenever the form reloads itself , it forgets what was selected.
All my other fields remember their values using this:
<input type="text" name="postcode" value="<?php echo $_POST['postcode']; ?> " />
How do I use the $_POST value to automatically select the option in the select field that was done by the user?
I tried this:
<select name="postage" selected="<?php echo $_POST['postage']; ?>" >
and this
<select name="postage" value="<?php echo $_POST['postage']; ?>" >
Thanks
You almost got it. You need to set the attribute selected="selected" (the exact form you need technically depends on your HTML doctype, but this is a safe default) on the <option> element if and only if the value of $postage equals the value of the element. So:
<select name="postage">
<option value="foo"
<?php if ($_POST['postage'] == "foo") echo 'selected="selected" '; ?>
>
</select>
Note that this violates the DRY principle because you now have two occurrences of the string "foo" in there, so it's a prime candidate for refactoring. A good approach would be to keep value/text pairs in an array and iterate over it with foreach to produce the <option> tags.
You need to foreach through all the options.
Make an array with all the dropdown options, loop through that, and compare with what is stored in post.
E.G.:
<?php
$aDropd = array("apple","orange","banana");
echo "<select>";
foreach($aDropd as $sOption){
$sSel = ($sOption == $_POST['postage'])? "Selected='selected'":"";
echo "<option $sSel>$sOption</option>";
}
echo "</select>";
no its not working at all..you need to put some kind of loop for that.
For Example : foreach($record => $values){
if($values == $_POST['postage']){
$selected = "selected='selected' ";
}else{
$selected = "";
}
}
<input name="postage" value="1" <?=$selected?> >
EDITED:
if($_POST['postage'] == 1){
$selected1 = "selected='selected' ";
}else if($_POST['postage'] == 2){
$selected2 = "selected='selected' ";
} and so on..........
<select name="postage">
<option value="1" <?=$selected1;?> />
<option value="2" <?=$selected2;?> />
</select>
I think this may be helpful to you..you can ask me if anything else needed...
Thanks.
The value of selected should be selected
<select name="postage" value="1" <?php echo (($_POST['postage'] == 1)?'selected="selected"':''); ?> >
Your html syntax is wrong. The correct way to write the html is like this:
<select>
<option value ="<?php echo $_POST['postage']; ?>" selected="selected"></option>
</select>
You can also make it shorter:
<select>
<option value ="<?=$_POST['postage']; ?>" selected="selected"></option>
</select>
<select name="foo">
<option value="1" <?php echo strcmp($_POST['foo'],"1")==0?"selected=\"selected\"":"" ?>>option1</option>
<option value="2" <?php echo strcmp($_POST['foo'],"2")==0?"selected=\"selected\"":"" ?>>option2</option>

Categories