Jump to content

Loops killing MySQL queries?


sorenchr

Recommended Posts

Hi!

 

I have a simple script:

 

$query = mysql_query("SELECT * FROM users WHERE user='$username' ORDER BY user");

$userRange = range('A', 'Z');

foreach ($userRange as $sorter) {

while($output = mysql_fetch_assoc($query)) {

	$substr = substr($output['userdata'], 0, 1);

	if($substr == $sorter) {

		echo $output['userdata'];		

	}

        echo "<br>";

}

}

 

It creates a loop where it spits out the userdata designated to a given username in an alphabetical order. The problems I am experiencing, is that it only outputs the userdata starting with A, then the loop sort of kills the MySQL query. So in order to fix this problem, i have to create a new MySQL query for each new letter in the alphabet, which i am not interested in :/

 

So does anybody have a solution for maintaining the query for use in the loop?

Link to comment
https://forums.phpfreaks.com/topic/111290-loops-killing-mysql-queries/
Share on other sites

just curious, but why don't you just do this?

 

$query = mysql_query("SELECT * FROM users WHERE user='$username' ORDER BY userdata");

while($output = mysql_fetch_assoc($query)) {
   echo $output['userdata'];
}

 

I mean, I'm assuming that user is unique, so I don't really see the point in ordering by user...

$query = mysql_query("SELECT * FROM users WHERE user='$username' ORDER BY userdata");

while($output = mysql_fetch_assoc($query)) {
   if (!$prev) $prev = substr($output['userdata'],0,1);
   echo $output['userdata'] . "<br />";
   $prev = substr($output['userdata'],0,1);
}

 

edited for: forgot to change it from my test loop vars to your vars

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.