Page 1 of 1

PHP Foreach in Array [SOLVED]

Posted: Sat Apr 07, 2007 1:32 am
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

Posted: Sat Apr 07, 2007 3:56 am
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

Posted: Sat Apr 07, 2007 4:55 am
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.