?
Solved

php foreach loop

Posted on 2013-05-14
10
Medium Priority
?
309 Views
Last Modified: 2013-06-02
Question:
I have a good idea what the attached  code  is doing but could someone please explain exactly what these parts are doing - step by step please:

I understand the insert command but not too sure of the foreach part and the entered data
code.txt
0
Comment
Question by:doctorbill
  • 3
  • 3
  • 3
  • +1
10 Comments
 
LVL 6

Assisted Solution

by:nickinthooz
nickinthooz earned 1000 total points
ID: 39165759
	foreach ($_POST[qty] as $key => $value) {
	//this is basically saying that for each post variable of quantity (for each item submitted in the form under quantity)
	// which loops through getting the key and value of each item
	if ($value) {
	// Then they are using a conditional to assure that the $value variable actually contains anything
	// if not, then it skips the mysql insert
	
	//then you can see where they are inserting in to the database, all the variables that have been set
	mysql_query("INSERT INTO ordered_items (oitem_order, oitem_item, oitem_price, oitem_code, oitem_qty) VALUES
				(
					'".$oid."',
					'".$key."',
					'".$_POST[price][$key]."',
					'".$_POST[code][$key]."',
					'".$value."'
				)
			");
		}
	}
	///////

Open in new window

I did further commenting although it's commented very well telling you what's happening.  In short, it's going through each of the post quantity items submitted and checking to see if there is a value before putting them in to the database.

For instance, if you have a form with 10 quantity fields, and only 4 are filled out, it's getting the value of those 4, inserting them in to the database and ignoring the ones that don't have a value.
0
 

Author Comment

by:doctorbill
ID: 39165832
what exactly is going on here:

'".$key."',
                              '".$_POST[price][$key]."',
                              '".$_POST
[$key]."',

Open in new window

0
 
LVL 6

Assisted Solution

by:nickinthooz
nickinthooz earned 1000 total points
ID: 39165904
The post variable is coming from the form as an array like so:

$price = array(1.00, 2.56, 3.49, 4.68)

what $key => $value does is basically take the above and make it:

$key         $price

price        1.00
price        2.56
price        3.49
price        4.68

with price being the "key" and the amount being the "value".  Instead of it coming in with 4 different entries, by putting it in array form it allows you to get one variable and divide them up with the code.  Take a look at these two:

http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.array.php
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 45

Accepted Solution

by:
Chris Stanyon earned 664 total points
ID: 39165910
As nick says, it's looping through an array of data that's been POSTed to your script. Those lines are just creating the SQL INSERT statement, which by-the-way is not a very safe way to do it - it is entering data straight into your database without any sanitization!!

It's a common way to have an array of data for things like a shopping cart. Assume you have three products in your cart, with IDs of product1, product2, and product3. Your POST data might look something like this:

$_POST[qty][1] = 5
$_POST[price][1] = £19.00
$_POST[code][1] = 'product1'

$_POST[qty][2] = 7
$_POST[price][2] = £5.00
$_POST[code][2] = 'product2'

$_POST[qty][3] = 5
$_POST[price][3] = £10.99
$_POST[code][3] = 'product3'

Open in new window

First time through the loop - foreach ($_POST[qty] as $key => $value)

$key = 1
$value = 5
$_POST[price][$key] = £19.00
$_POST[code][$key] = product1

Open in new window

Assuming $oid has been set to ORDER1, your SQL STATEMENT look likes this:

INSERT INTO ordered_items
(oitem_order, oitem_item, oitem_price, oitem_code, oitem_qty)
VALUES
('ORDER1', '1', '£19.00', 'product1', '5');

Open in new window

Second time through the loop and your SQL Statement looks like this:

INSERT INTO ordered_items
(oitem_order, oitem_item, oitem_price, oitem_code, oitem_qty)
VALUES
('ORDER1', '2', '£5.00', 'product2', '7');

Open in new window

Hope that helps :)
0
 

Author Comment

by:doctorbill
ID: 39165930
so $key is refering to a position in an array ?
0
 
LVL 45

Expert Comment

by:Chris Stanyon
ID: 39165955
Impossible to say! Don't know how you've created your form.

Look at the source of your form before POSTing it - the $key value is the bit that appears in the 'name', so if your form field is called something like qty['xyz'] then the 'xyz' bit is what gets read as the $key value. They'll be some other code somewhere that creates these names!
0
 
LVL 45

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 664 total points
ID: 39165975
You just changed your comment while I was replying. It may not be the position - it could be anything:

$_POST[qty]['xyz'] = 5
$_POST[price]['xyz'] = £19.00
$_POST[code]['xyz'] = 'product1'

$_POST[qty]['test1'] = 7
$_POST[price]['test1'] = £5.00
$_POST[code]['test1'] = 'product2'

$_POST[qty]['cheese'] = 5
$_POST[price]['cheese'] = £10.99
$_POST[code]['cheese'] = 'product3'

Open in new window

If the above array is POSTed then $key will equal xyz, test1 and cheese on subsequent loops through your array!

The $key part is being inserted into oitem_item column in your table, but we have no way of knowing what that's for.
0
 
LVL 6

Assisted Solution

by:nickinthooz
nickinthooz earned 1000 total points
ID: 39166041
0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 336 total points
ID: 39168002
Don't use this code.  It is a security risk because it uses external variables without any "sanity checks" or preparation for use in a query.  And if the query fails, the script will not detect the failure so your data base is at risk of silent corruption and data loss.  I would fire a programmer who wrote something like this.

And in related news, you need to get off MySQL because PHP is removing it.  This article tells why that is happening and gives the step-by-step instructions for what you must do to keep your scripts working.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

When you want to see what is contained in a variable you can use this function:
http://php.net/manual/en/function.var-dump.php

Example: var_dump($_POST);

If you look at the HTML form and the contents of the request variable ($_GET, $_POST) you will find a relationship.
http://us1.php.net/manual/en/tutorial.forms.php
0
 

Author Closing Comment

by:doctorbill
ID: 39214487
solved
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month13 days, 20 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question