Jump to content

Capture conditional posted variables into an array then loop


victusinambitus

Recommended Posts

I have an order form that is populated dynmically from a database. We have no control over the number of "active" items at the time the form is generated however the format of the fields is defined as: $item_[n], where [n] is the database record ID.

 

<?php $sql="select * from products where active=1 order by 'order' "; 
$result1=mysql_query($sql); 
$no=mysql_num_rows($result); 
for($i=0;$i<$no;$i++) {
    $products_id=trim(mysql_result($result1,$i,"products_id")); ?>
    <HTML OUTPUT HERE>Item: <input type="text" name="item_<?php echo $products_id; ?>"size="1" />
<?php } ?>

 

All is well so far, however after posting this data I wish to capture the posted data into an array and then process it.

 

I have it fully working hard coded thus:

 

<?php if(array_key_exists('item_1', $_POST)) {
    $item_1=$_POST['item_1'];
    if ($item_1>0) {
    <DATA PROCESSING CODE HERE>
    } 
} else {
    $item_1=""; 
}
<?php if(array_key_exists('item_2', $_POST)) {
    $item_2=$_POST['item_2'];
    ...
    etc

 

Obviously I wish to automate this by putting all posted data into an array and then looping through those items in the array. Can someone please help me put conditional posted data (where for example they commence with "item_") into an array and then complete the code looping through the variables in the array?

 

<CAPTURE CONDITIONAL POSTED DATA INTO AN ARRAY HERE>
<FOR LOOP BEGINS>
    <DATA PROCESSING CODE HERE USING THE <field from array>>
<FOR LOOP ENDS>

 

Thank you

Link to comment
Share on other sites

It would be much simpler to set up all of the form fields that will be processed the same way as an array.

 

<form method="post>
<input name="item[]" type="text">
<input name="item[]" type="text">
<input name="item[]" type="text">
<input name="item[]" type="text">
<input name="item[]" type="text">
<input name="item[]" type="text">
<input name="item[]" type="text">
<input type="submit">

 

$_POST['item'] = array_map('trim', $_POST['item']);
foreach( $_POST['item'] as $v ) {
        if( !empty( $v ) {
                // validate data and do whatever it is you want to do here . . .
        }
}

Link to comment
Share on other sites

Thanks to the people who have responded. Much appreciated. :D  Apologies but I still do not have a grasp on the solutions provided. Sorry if I didn't make myself clear and (for Spring) my understanding of arrays and loops is limited to copying others' existing code and modifying.

 

I think it may be better for me to ask the question another way:

 

I have a form that posts data. A var_dump($_POST) in the receiving code may produces for example this:

 

array(3) { ["item_273"]=> string(1) "1" ["item_107"]=> string(1) "5" ["item_65"]=> string(2) "10" }

 

As a result of this sample post I need to then have the following variables available in my receiving PHP code:

 

$item_16="1";
$item_273="5";
$item_65="10;

 

I will then loop through each item in the array, search the database for further information on each item such as say, price and weight:

 

$item_16_price="1.00";
$item_273_price="2.00";
$item_65_price="3.00";

 

and,

 

$item_16_weight="5";
$item_273_weight="10";
$item_65_weight="3";

 

and then total values to calculate total weight and total price:

 

$total_price=$item_16*$item_16_price;
$total_weight=$item_16*$item_16_weight;

 

to be able to build one results string:

 

$order="You have ordered:<br />";
$order.="Item: 16, Qty: 7, Weight: 5kg<br />";
$order.="Item: 273, Qty: 7, Weight: 5kg<br />";
$order.="Item: 65, Qty: 7, Weight: 5kg<br />";
$order.="Total Price: $41.00<br />";
$order.="Total Weight: 85kg<br />";

 

Using:

 

echo $order;

 

I can now produce the desired output:

 

You have ordered:

Item: 16, Qty: 7, Weight: 5kg

Item: 273, Qty: 7, Weight: 10kg

Item: 65, Qty: 7, Weight: 3kg

Total Price: $41.00

Total Weight: 53kg

 

I have supplied my "quasi" code again for your assistance.

 

//a) code here to set variables:
$item_16="1";
$item_273="5";
$item_65="10;

//b) code here to loop through the database picking up additional values for the three posted items like:
SELECT price,weight FROM PRODUCTS WHERE products_id={array value here}
$item_16_price="1.00";
$item_273_price="2.00";
$item_65_price="3.00";
$item_16_weight="5";
$item_273_weight="10";
$item_65_weight="3";

//c) looping finished and all variables set and available for use
$total_price=$item_16*$item_16_price;
$total_weight=$item_16*$item_16_weight;

//d) my outputing code for example that may calculate total weight and/or total price
//e) use all variables

Link to comment
Share on other sites

We do indeed understand what you get from the form. What we've recommended is to change the form, so that you change what you get from it.

You can have PHP automatically create the array for you, by adding [] to the name of the input fields. Put something between those square brackets, and it becomes the key for the value in that particular row. If it doesn't have a predefined key, it'll get assigned one per normal auto-indexing routines.

 

In other words, if you have a form that looks like this:

<form method="post" action="">
<table>
	<thead>
		<tr>
			<th>Item</th>
			<th>Price</th>
			<th>Amount</th>
			<th>Total</th>
		</tr>
	</thead>
	<tbody>
<!-- This is the looping part. -->
		<tr>
			<td>{$ItemName}</td>
			<td>{$ItemPrice}</td>
			<td><input type="text" name="item[$ItemID]" value="$ItemAmnt"></td>
			<td>{$ItemTotal}</td>
		</tr>
<!-- End of the looping part. -->
	</tbody>
</table>

<fieldset>
	<input type="submit" name="submit" value="Update cart">
</fieldset>
</form>

 

The resulting $_POST array would have an index named item, which would be an array containing the item ID as the keys with the as the value. Like this:

foreach ($_POST['item'] as $ItemID => $Amount) {}

 

In closing I would recommend you to go to the PHP manual, and read up on arrays and everything else mentioned here that you don't understand fully. Once you fully understand how array works, and how you can manipulate them and the $_POST superglobal, things will become a lot easier for you.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.