Jump to content

[SOLVED] Loop problem


DeepakJ

Recommended Posts

foreach ($invoicenumlist as $key => $value){
	$query3 = "SELECT * FROM productid WHERE invoicenum='$value'";
	$Result3=mysql_query($query3) or DIE("Could not query3");
	while ($row3=mysql_fetch_array($Result3)){
		echo "hello";
		$productidlist[]= $row3['productid'];
		if ($row3['productid']!= ""){
			$pidcounter=$pidcounter+1;
		}
	}
}

 

Can you see what is wrong with this loop?

I tested partsof it and saw that it entered the foreach loop but not the while loop? Can someone please explain why?

Link to comment
https://forums.phpfreaks.com/topic/62680-solved-loop-problem/
Share on other sites

:P I have another question. How could you define a multi dimensional array in another multidimensional array.

 

$pidcounter = 0;
foreach ($invoicenumlist as $key => $value){
foreach ($invoicenumlist[$key] as $key1 => $value1){
	$query3 = "SELECT * FROM productid where invoicenum = '$value1'";
	$Result3 = mysql_query($query3);
	while ($row3=mysql_fetch_array($Result3)){
		$productidlist[$key][]=$row3['productid'];
		$pidcounter = $pidcounter+1;
	}

}
}

 

Hopefully above will help illustrate what I am trying to do.

Link to comment
https://forums.phpfreaks.com/topic/62680-solved-loop-problem/#findComment-312900
Share on other sites

Not sure I follow. Are you wanting to define the array or iterrate through it?

 

The code you have above is VERY bad form. You should never have nested loops to run queries such a that, it put a greal of unneccessary stress on the server. Also, this $invoicenumlist[$key] is the same as $value from the first loop. You do not need to have a variable for the key in a foreach loop and you should use meaningful names for the variables, not just $key and $value.

 

Also, no need to use $pidcounter, just use count() any time you need to know how many records there are in an array.

 

Here is a better way of accomplishing the above. It still has a looping query, but not two:

foreach ($invoicenumlist as $invoiceKey => $invoicenums){

    $query = "SELECT * FROM productid where invoicenum IN (" . implode(',', $invoicenums) . ")";
    $Result = mysql_query($query);

    while ($row=mysql_fetch_array($Result)){
        $productidlist[$key][]=$row3['productid'];
    }

}

 

 

Link to comment
https://forums.phpfreaks.com/topic/62680-solved-loop-problem/#findComment-313338
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.