PHP Foreach in Array [SOLVED]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
matth2004
Forum Commoner
Posts: 40
Joined: Wed Sep 06, 2006 3:26 am

PHP Foreach in Array [SOLVED]

Post by matth2004 »

Hi,

I'm having problems getting this array to work:

Code: Select all

	
$pieces = explode("<br>", $tempitems);
	foreach ($pieces as $codeitems) {
	$query = "SELECT * FROM techlist_items";
	$result = mysql_query($query);
	if($result) {
		while($row = mysql_fetch_array($result)){
			$tempname = $row["name"];
			$tempcode = $row["code"];
			if ($tempcode == $codeitems) {
			$maincontent .= "<a href=\"?act=show&code=".$items."\">".$tempname."</a><br>";
			}
		}
	}
	}
$tempitems is retrieved from the database in previous code and contains a list of items for a certain order using the item code. i.e. DISC-042007. $pieces is the array which is an array of all the different items split by using <br> because each item has a <br> between it in $tempitems. I then use a foreach statement which works perfectly well when I just have:

Code: Select all

$maincontent .= "<a href=\"?act=show&code=".$items."\">".$items."</a><br>";
in the foreach statement, but my aim is to get each code, connect to the database of items and convert all those codes into proper names like Discount Coupon for the code DISC-042007 etc. The thing is, when I add the database code, it only displays the first item and not the other one. I have tried using several different combinations of items in $tempitems and switched them around but it only displays the first one and does not continue throughout the array. Any ideas?

Regards,
Matt
Last edited by matth2004 on Sat Apr 07, 2007 3:56 am, edited 1 time in total.
matth2004
Forum Commoner
Posts: 40
Joined: Wed Sep 06, 2006 3:26 am

Post by matth2004 »

I used:

Code: Select all

$pieces = explode("|sep|", $tempitems);
while (list ($key, $val) = each ($pieces)) {
	$query="SELECT * FROM techlist_items WHERE code='$val'";
	$result=mysql_query($query);
	
	$num=mysql_numrows($result);
	
	$i=0;
	while ($i < $num) {
	$tempname=mysql_result($result,$i,"name");
	$tempcode=mysql_result($result,$i,"code");
	
	if($tempcode == $val) {
	$maincontent2 .="<a href=\"?act=show&code=".$val."\">".$tempname."</a><br>\n";
	}
	$i++;
	}
}
And it works.

Regards,
Matt
bubblenut
Forum Newbie
Posts: 20
Joined: Sat Feb 03, 2007 4:16 am
Location: London

Post by bubblenut »

As a performance improvement, you could move the db query outside the outer loop, put the results into an array and then loop over that array instead of running the query over and over. This way you would only ever run the query once.
Post Reply