Solved

php foreach loop

Posted on 2013-05-14
10
304 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 250 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 250 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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 166 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 43

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 43

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 166 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 250 total points
ID: 39166041
0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 84 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

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

825 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