Page 1 of 1

Loop question.

Posted: Tue Jul 22, 2003 1:40 pm
by Goober
Hello.

I queried a database, received certain desired values. If there is an email address entry in a row, I echo it in such a manner:

Code: Select all

for( $count = 1; $all_rows = mysql_fetch_row( $get_all ); ++$count )
	  {
       if( $all_rowsї3] )
		     {
		   echo $all_rowsї3] . ", ";
          }
     }
Does anyone have any theories as to how I can code this loop so that if it's on the last entry, it won't include the comma in the echo?

Thanks,
Goober

Posted: Tue Jul 22, 2003 1:49 pm
by Stoker

Code: Select all

<?php
 $comma = '';
 while ($row =  mysql_fetch_row($resultpointer))
 {
    if ($row[3])
    {
       echo $comma . $row[3];
       if (!$comma) $comma = ', ';
    }
 }
?>

Posted: Tue Jul 22, 2003 1:49 pm
by AVATAr
1) try not to put the mysql_fetch_row in the "for". assign that value to a variable to use it in the "for" statement.

2) check mysql_num_rows

Posted: Tue Jul 22, 2003 1:50 pm
by PaTTeR

Code: Select all

$records_count = mysql_num_rows($get_all)
$i = 0;
while ($row = mysql_fetch_array($get_all)) {
    $i++;
     if ($row[3]) {
         echo $row[3];
         echo ($record_count == $i) ? '' : ',  ';
     }
}
hmmm this should work corectly only if you have an e-mail seted in last row.

there is other idea :lol:

Code: Select all

<?php
while ($row = mysql_fetch_array($get_all)) {
    if ($row[3]) {
        $result_str .= $row[3].', ';
    }
}

echo substr($result_str, 0, strlen($result_str) - 2);
?>

...

Posted: Tue Jul 22, 2003 1:57 pm
by kettle_drum
Umm you could always do a query before hand to get the number of results that it will give you. And then use this data to know what the last result is, and then do an if result == last { dont print comma}

You could also maybe also print the comma before you print the result and have a counter that is incremented each time you post the data from the database, and then only print the comma if the counter <> 0.

Posted: Tue Jul 22, 2003 2:04 pm
by Stoker
No point vasting resources on extra function calls and variables, as you can see my "solution" only uses one variable and no extra function calls..

Posted: Tue Jul 22, 2003 5:57 pm
by Goober
Thanks.