Jump to content

Iterating through $_POST array


HanneSThEGreaT

Recommended Posts

Hi. First timer here.

 

I'm trying to iterate through 5 arrays in a foreach loop. Yep, I know you'll say just use a counter that increments. Sadly, that gives me horrendous results! So, I am using the next & current methods of arrays. Thing is, it gives me bad results ( items that weren't even chosen on the next page ), or it leaves the first couple of items out. I did this :

 

		<?php

		$ID = array();
		$NAME = array();
		$PRICE = array();
		$QUANT = array();
		$checkCount = 0;

		foreach (array_keys($_POST) as $key) 
		{ 

			$$key = $_POST[$key]; 

			$iPos = strpos($key, "ID");

			$nPos = strpos($key, "NAME");
			$pPos = strpos($key, "PRICE");
			$qPos = strpos($key, "QUANT");
			$cPos = strpos($key, "CHECK");

			if ($iPos !== false)
			{
				$ID[] = $$key;
			}
			else
			{
				//echo "The string ID was not found in the string ";
			}

			if ($nPos !== false)
			{
				$NAME[] = $$key;
			}
			else
			{
				//echo "The string NAME was not found in the string ";
			}						

			if ($pPos !== false)
			{
				$PRICE[] = $$key;
			}
			else
			{
				//echo "The string PRICE was not found in the string ";
			}				

			if ($qPos !== false)
			{
				$QUANT[] = $$key;
			}
			else
			{
				//echo "The string QUANT was not found in the string ";
			}

			if ($cPos !== false) 
			{				
				$checkCount++;

				if ($checkCount == 1)
				{

					echo "Product ID <input type = 'text' name = 'ID" . current($ID) . "' value = '" . current($ID) . "'></br>";
					echo "Product Name <input type = 'text' name = 'NAME" . current($NAME) . "' value = '" . current($NAME) . "'></br>";
					echo "Product Price <input type = 'text' name = 'PRICE" . current($PRICE) . "' value = '" . current($PRICE) . "'></br>";
					echo "Product Quantity <input type = 'text' name = 'QUANT" . current($QUANT) . "' value = '" . current($QUANT) . "'></br>";
					}

					if ($checkCount > 1)
					{
					echo "Product ID <input type = 'text' name = 'ID" . next($ID) . "' value = '" . next($ID) . "'></br>";
					echo "Product Name <input type = 'text' name = 'NAME" . next($NAME) . "' value = '" . next($NAME) . "'></br>";
					echo "Product Price <input type = 'text' name = 'PRICE" . next($PRICE) . "' value = '" . next($PRICE) . "'></br>";
					echo "Product Quantity <input type = 'text' name = 'QUANT" . next($QUANT) . "' value = '" . next($QUANT) . "'></br>";
    				}
    				
			} 
			else 
			{
     				//echo "The string CHECK was not found in the string ";
			}



		}
?>

 

You will see I did all the processing under the CHECK if statement, the reason for this is, it is easier to identify the items ordered because they have been checked on the previous page.

 

Link to comment
Share on other sites

Hi. Thanx for your reply :)

 

Here is my form code :

 

<p>When ordering, please select the checkbox ( the little square ) next to the word <b>Order</b>, then, type in the quantity that you'd like to order in the column next to it. Once you are done selecting your items, please click on the Proceed to next Step</b> button at the bottom of the products list<b></p>
<p> </p>
<FORM Name="TNMItems" Id = "TNMItems" method="Post" action="order.php">
<table border="1" cols="7" bordercolor="#000080" width="100%">
<tr>
<th width = "14.2%">ID</th>
<th width = "14.2%">Name</th>
<th width = "14.2%">Description</th>
<th width = "14.2%">Product</th>
<th width = "14.2%">Price</th>
<th width = "14.2%">Order?</th>
<th width = "14.2%">Quantity</th>
</tr>
<? 
// Connect to MySQL server first . You can use variables instead of these literals
$db = mysql_connect('localhost', 'yvonnedp', 'yvonne');

if (!$db) {
   echo 'Could not connect to MySQL server. <br />Error # ', mysql_errno(), ' Error msg: ',  mysql_error();
       exit;
       }

// Select the database you want to use � You can use a variable here too instead
if (!mysql_select_db('tnm', $db))
{
    // Did selection fail?
    // Handle error
         echo 'DB Selection failed. <br />Error # ', mysql_errno(), ' Error msg: ', mysql_error();
       exit;
}
       
// An example for retrieving zero or more rows
$sql = "SELECT * FROM Products";

$result = mysql_query($sql, $db);

if (!$result) {
    // Handle error
         echo 'Query failed. SQL: ', $sql, '<br />Error # ', mysql_errno(), ' Error msg: ', mysql_error();
   exit;
}

   // The while loop stops when there's no data left; it might not even go in loop
   // and echo anything when there's no data returned on the first call to
   // mysql_fetch_assoc()

while($row = mysql_fetch_assoc($result)) {
  // Retrieve data until no more
      echo "<tr valign='top'><td>";
      echo $row['ProdID'], "<input type='hidden' name='ID_" . $row['ProdID'] . "' value='" . $row['ProdID'] . "'></td><td>";
      echo $row['ProdName'], "<input type='hidden' name='NAME_" . str_replace(" ", "%20", $row[ProdName]) . "' value='" . $row['ProdName'] . "'></td><td>";
      echo $row['ProdDesc'], '</td><td>';
      echo "<IMG SRC='images/" . $row['ProdImg'], "' height='100' width='100'></td><td>";      
      echo $row['ProdPrice'], "<input type='hidden' name='PRICE_" . $row['ProdPrice'] . "' value='" . $row['ProdPrice'] . "'></td>";
      echo "<td class= 'Multi'><input type = 'checkbox' value=" . str_replace(" ", "%20", $row[ProdName]) . " name='CHECK_'>Order? <input type = 'hidden' name = 'checks'></td>";
      echo "<td align='center' class= 'Multi'>How Many?<br><input type = 'text' name = 'QUANT_" . str_replace(" ", "%20", $row[ProdName]) . "' size='4'></td></tr>";      
      }
?>

<tr><td colspan="7" align="center"><input type="submit" value="Proceed to Checkout" onclick="GetChecks();"></td></tr>
</table></form> 

 

I am attaching the two filess in question

 

[attachment deleted by admin]

Link to comment
Share on other sites

Your form code is very messy and kind of all over the place, no offence, but at least it explains what you are trying to do (somewhat).

I am assuming that the CHECK part of your order.php page is so you can display to the customer what they have selected based on the form?

 

May I suggest a much cleaner solution (in regards to the form and the big processing script, it will require A LOT of changes)

Link to comment
Share on other sites

We've all gotta start somewhere right :)

What I would do in the form is to create a HTML array of the selected products with the product_id assigned to the value.

Then each of the names, qtys etc will also be a HTML array

(Crude example warning: A HTML array is basically assigning [] to the name, so name="something[]" can be accessed in PHP with $_POST['something'][0])

 

Ill post an example soon.

 

Link to comment
Share on other sites

Form code:

while ($row = mysql_fetch_assoc($result)) {
// Retrieve data until no more
echo '<tr valign="top">
	<td>' , $row['ProdID'], '</td>
	<td>' , $row['ProdName'] , '<input type="hidden" name="product[' , $row['ProdID'] , '][name]" value="' , $row['ProdName'] , '" /></td>
	<td>' , $row['ProdDesc'] , '</td>
	<td><img src="images/' , $row['ProdImg'] ,'" height="100" width="100"></td>
	<td>' , $row['ProdPrice'] , '<input type="hidden" name="product[' , $row['ProdId'] , '][price]" value="' , $row['ProdPrice'] , '" /></td>
	<td class="Multi"><input type="checkbox" value="' , $row['ProdID'] , '" name="ordered" /> Order?</td>
	<td align="center" class="multi">How Many?<br/><input type="text" name="product[' , $row['ProdId'] , '][qty]" size="4" /></td>
</tr>';  
}

The array is basically

ordered -> Contains a list of ProdID from the "checked" checkboxes (only checked boxes are passed)

products -> A multi-dimensional array which has an initial key of ProdID, inside that array is the keys of qty, price and name.

So, if somebody selects, lets say ProdID 2.

Ordered will contain a value of 2

Then you can look at the product array for the data relating to 2

$prod = $_POST['product'][2]; //will return an array with qty, name and price as keys, so
echo $prod['name']; // may result in Pantaloons, as that is what product 2 is

 

Once you have got this part squared away in the knowledge bank, ill show you the other part.

And of course let me know if what I am saying is completely confusing :)

Link to comment
Share on other sites

Wow, OK, so this is how to get the items stored in a multi array, OK, it doesn't look too complicated :)

Thank you so much for your efforts so far!

 

I also didn't realise you can use echo like that with each comma representing something to write, so I have already learnt a great deal! thanks

Now on the next page ( order.php ), I wrote :

 

$prod = $_POST['product'][2]; //will return an array with qty, name and price as keys, so
echo $prod['name']; // may result in Pantaloons, as that is what product 2 is

And it just showed me a blank page

Link to comment
Share on other sites

I tried to make this as easy as possible, fill your brain with the good stuff.

Remember that a , used for concatenation can only be done so for ECHO statements. You cant use it for concatenation of variables and such.

 

The example I posted was basically usless, it assumes that ProdID 2 was selected on the main page.

Also, for development you should always have error_reporting turned on, it will give you a display of any errors your script is generating and help you nail down what went wrong.

 

//top of the page
error_reporting(E_ALL);
ini_set('display_errors',1);

 

Ill now get the other part for you :)

Link to comment
Share on other sites

Ive created 2 versions for you to take a look at, both will do the exact same job. (Assuming I havent assed something up along the way)

// This is one way to do it and because I am bored, I will write a second method for you as well
// This makes sure somebody actually selected a product
if (isset($_POST['ordered'])) {
// We can assign $_POST['products'] to a variable to make it easier to type out
$prod = $_POST['products'];
// Throw a little intro to see how many they checked
echo 'You selected ' , count($_POST['ordered']) , ' products.';
// Now we loop through it and get the IDS that were selected
// Foreach lets you select the $key and the $value for each iteration of the loop //
foreach ($_POST['ordered'] as $key=>$id) {
	echo 'Selected Index: ' , $key , '<br/>
	ProdID: ' , $id , '<br/>
	ProdName: ' , $prod[$id]['name'] , '<br/>
	ProdPrice: ' , $prod[$id]['price'] , '<br/>
	ProdQty: ' , $prod[$id]['qty'] , '
	<hr/>';
}
}

// Start of method 2, this one will be "driven" by the PRODUCT array
if (isset($_POST['ordered'])) {
// create a variable to store the information of ordered
$ordered = $_POST['ordered'];
// Throw a little intro to see how many they checked
echo 'You selected ' , count($ordered) , ' products.';
// Loop through all the products posted, they will all be posted but we only need the ones checked so we will have to filter
foreach ($_POST['product'] as $id=>$product_array) {
	// this is the filter
	if (in_array($id,$ordered) {
		// It was selected, Yay!
		echo 'Selected Index: ' , $id , ' (not really needed to be shown)<br/>
		ProdID: ' , $id , '<br/>
		ProdName: ' , $product_array['name'] , '<br/>
		ProdPrice: ' , $product_array['price'] , '<br/>
		ProdQty: ' , $product_array['qty'] , '
		<hr/>';
	} else {
		// You dont need this section but it will be actioned when a product wasnt selected
	}
}
}

I got a little carried away

Link to comment
Share on other sites

You're a genius!!

 

I do understand all the codes and your logic, as I am accustomed to .NET langueges.

 

I tried to implement your code on my order page, and it only says :

 

You selected 1 products.

Eventhough I have selected 5 products, it also doesn't list the product(s) selected.

 

Am I doing something wrong?

 

I have included this in my Products page :

 

while ($row = mysql_fetch_assoc($result)) {
// Retrieve data until no more
echo '<tr valign="top">		<td>' , $row['ProdID'], '</td>		<td>' , $row['ProdName'] , '<input type="hidden" name="product[' , $row['ProdID'] , '][name]" value="' , $row['ProdName'] , '" /></td>		<td>' , $row['ProdDesc'] , '</td>		<td><img src="images/' , $row['ProdImg'] ,'" height="100" width="100"></td>		<td>' , $row['ProdPrice'] , '<input type="hidden" name="product[' , $row['ProdId'] , '][price]" value="' , $row['ProdPrice'] , '" /></td>		<td class="Multi"><input type="checkbox" value="' , $row['ProdID'] , '" name="ordered" /> Order?</td>		<td align="center" class="Multi">How Many?<br/><input type="text" name="product[' , $row['ProdId'] , '][qty]" size="4" /></td>	</tr>'; 
}

 

And I have included this into my order page :

 

// This makes sure somebody actually selected a product
if (isset($_POST['ordered'])) {
// We can assign $_POST['products'] to a variable to make it easier to type out
$prod = $_POST['products'];
// Throw a little intro to see how many they checked
echo 'You selected ' , count($_POST['ordered']) , ' products.';
// Now we loop through it and get the IDS that were selected
// Foreach lets you select the $key and the $value for each iteration of the loop //
foreach ($_POST['ordered'] as $key=>$id) {
	echo 'Selected Index: ' , $key , '<br/>
	ProdID: ' , $id , '<br/>
	ProdName: ' , $prod[$id]['name'] , '<br/>
	ProdPrice: ' , $prod[$id]['price'] , '<br/>
	ProdQty: ' , $prod[$id]['qty'] , '
	<hr/>';
}
}

 

Maybe your eyes are better than mine, in identifying my mistake(s)

Link to comment
Share on other sites

Do you wanna attach both of the scripts here and ill get able to get a better look (i have had a few brewskis at this point)

 

Edit: Scrap that..

I know what I did wrong :) name="ordered" should be name="ordered[]" on the checkboxes

And I have the name of the products as "product" but PHP is looking for products

Link to comment
Share on other sites

You are geniunely kind, and I am geniunely stupid LOL!

 

You talked about the HTML array at the beginning, and I already forgot that!  :o

 

This thing has kept me busy for some time, and you have taught me a great deal.

I like this forum, and don't be surprised if you see more of me :)

 

Anyways, that almost did the trick, I now get this :

 

You selected 5 products.Selected Index: 0
ProdID: 1
ProdName: 3 Days Show Slimming Ginseng Cream
ProdPrice: 
ProdQty: 
--------------------------------------------------------------------------------
Selected Index: 1
ProdID: 2
ProdName: Anti Stretchmark Cream
ProdPrice: 40.00
ProdQty: 
--------------------------------------------------------------------------------
Selected Index: 2
ProdID: 9
ProdName: Green Tea Easy Slim Activated Gel
ProdPrice: 
ProdQty: 
--------------------------------------------------------------------------------
Selected Index: 3
ProdID: 16
ProdName: The New Me Combo Pack 5
ProdPrice: 40.00
ProdQty: 
--------------------------------------------------------------------------------
Selected Index: 4
ProdID: 20
ProdName: True Beauty Mild Laxative Herbal Infusion Tea
ProdPrice: 40.00
ProdQty: 

 

When I select 5 products. Some of my quantities and prices are left out. I'll try to see if I can get it right though, but can you see what I am doing wrong ?

Link to comment
Share on other sites

Dont stress about forgetting, youve got plenty of code to look at and work through.

The only reason I can see for them being empty is because they are empty.

You can use

echo '<pre>' , print_r($_POST,true) , '</pre>';

to view the array that is sent from the form and see what that contains.

Link to comment
Share on other sites

Hello again. This is the output :

 

Array
(
    [product] => Array
        (
            [1] => Array
                (
                    [name] => 3 Days Show Slimming Ginseng Cream
                )

            [2] => Array
                (
                    [price] => 40.00
                    [name] => Anti Stretchmark Cream
                )

            [3] => Array
                (
                    [qty] => 2
                    [name] => Bath Salt
                )

            [4] => Array
                (
                    [price] => 40.00
                    [name] => Extended Fat Decreasing Hot Gel
                )

            [5] => Array
                (
                    [qty] => 2
                    [name] => Extra Strength Dieters. II True-Slim Tea
                )

            [6] => Array
                (
                    [price] => 50.00
                    [name] => Fruits + Vegetables Waist + Abdomen Slimming Capsules
                )

            [7] => Array
                (
                    [qty] => 
                    [name] => Gold Kangmei Slimming Capsules
                )

            [8] => Array
                (
                    [price] => 40.00
                    [name] => Good-Bye Cellulite Soap
                )

            [9] => Array
                (
                    [qty] => 
                    [name] => Green Tea Easy Slim Activated Gel
                )

            [10] => Array
                (
                    [price] => 60.00
                    [name] => Hip Up Cream - Coffee + Chilli
                )

            [11] => Array
                (
                    [qty] => 
                    [name] => Hot Long Chilli + Ginger Slimming + Fitting Cream
                )

            [12] => Array
                (
                    [price] => 130.00
                    [name] => Kangmei Diet Tea
                )

            [13] => Array
                (
                    [qty] => 
                    [name] => Red Kangmei Slimming Capsules
                )

            [14] => Array
                (
                    [price] => 90.00
                    [name] => Slimming + Detoxify Soap
                )

            [15] => Array
                (
                    [qty] => 
                    [name] => The New Me Combo Pack 4
                )

            [16] => Array
                (
                    [price] => 40.00
                    [name] => The New Me Combo Pack 5
                )

            [17] => Array
                (
                    [qty] => 2
                    [name] => The New Me Combo Pack 6
                )

            [18] => Array
                (
                    [price] => 40.00
                    [name] => The New Me Combo Pack 7
                )

            [19] => Array
                (
                    [qty] => 
                    [name] => The New Me Mini Combo Pack 1
                )

            [20] => Array
                (
                    [price] => 40.00
                    [name] => True Beauty Mild Laxative Herbal Infusion Tea
                )

            [21] => Array
                (
                    [qty] => 
                )

            [22] => Array
                (
                    [price] => 40.00
                )

            [23] => Array
                (
                    [qty] => 
                )

            [24] => Array
                (
                    [price] => 70.00
                )

            [25] => Array
                (
                    [qty] => 
                )

            [26] => Array
                (
                    [price] => 90.00
                )

            [27] => Array
                (
                    [qty] => 
                )

            [28] => Array
                (
                    [price] => 20.00
                )

            [29] => Array
                (
                    [qty] => 2
                )

            [30] => Array
                (
                    [price] => 180.00
                )

            [31] => Array
                (
                    [qty] => 
                )

            [32] => Array
                (
                    [price] => 220.00
                )

            [33] => Array
                (
                    [qty] => 
                )

            [34] => Array
                (
                    [price] => 160.00
                )

            [35] => Array
                (
                    [qty] => 
                )

            [36] => Array
                (
                    [price] => 200.00
                )

            [37] => Array
                (
                    [qty] => 
                )

            [38] => Array
                (
                    [price] => 70.00
                )

            [39] => Array
                (
                    [qty] => 
                )

            [40] => Array
                (
                    [price] => 60.00
                )

            [41] => Array
                (
                    [qty] => 2
                )

        )

    [ordered] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 8
            [3] => 14
            [4] => 20
        )

    [submit] => Proceed to Checkout
)

 

after I used :

 

echo '<pre>' , print_r($_POST,true) , '</pre>';{/code]

Link to comment
Share on other sites

You have no other code that is removing elements above the output code?

Do you have this on a server that we can see?

Im thinking that your FORM is causing an issue, can you post the HTML source of your form?

 

Hello again. Thanks for all your trouble.

 

To answer your questions :

 

1) Nope

2) yes, have a look at http://www.thenewme.co.za

3) The form is this part :

 

while ($row = mysql_fetch_assoc($result)) {
// Retrieve data until no more
echo '<tr valign="top">		<td>' , $row['ProdID'], '</td>		<td>' , $row['ProdName'] , '<input type="hidden" name="product[' , $row['ProdID'] , '][name]" value="' , $row['ProdName'] , '" /></td>		<td>' , $row['ProdDesc'] , '</td>		<td><img src="images/' , $row['ProdImg'] ,'" height="100" width="100"></td>		<td>' , $row['ProdPrice'] , '<input type="hidden" name="product[' , $row['ProdId'] , '][price]" value="' , $row['ProdPrice'] , '" /></td>		<td class="Multi"><input type="checkbox" value="' , $row['ProdID'] , '" name="ordered[]" /> Order?</td>		<td align="center" class="Multi">How Many?<br/><input type="text" name="product[' , $row['ProdId'] , '][qty]" size="4" /></td>	</tr>'; 
}

 

I am attaching products.php and order.php here. Thos are the only two files used for this.

 

[attachment deleted by admin]

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.