Jump to content

Help optimizing loop


fireballchad

Recommended Posts

<?php
$query = 'SELECT COUNT(*) FROM `fonts`';
$result = mysql_query($query) or die('Sorry, we could not count the number of results: ' . mysql_error());
$numberofresults = mysql_result($result, 0);
$numberofresults = $numberofresults + 1;
        /*** query the database ***/

$i=1;
        /*** loop over the results ***/
        while($i<$numberofresults)
        {
		$querySelect1 = "SELECT * FROM fonts WHERE id='$i'";
$resultSelect1 = mysql_query($querySelect1);
	$row2 = mysql_fetch_array($resultSelect1);
            /*** create the options ***/
            echo '<option value="'.$row2['id'].'"';
		if ($row2['id']==$font){
			echo "selected='selected'";
		}
            echo '>'.$row2['font']. '</option>'."\n";
		$i++;
        }
    
?>

 

Currently my site is still underdevelopment and I was having trouble creating a dynamically driven drop down to select which font the user wanted out of the selection that are available. I managed to get this to work just for proof of concept so I could move onto other things. Any help on how to get this to work in a more efficient manner would be greatly appreciated.

 

 

Link to comment
https://forums.phpfreaks.com/topic/257768-help-optimizing-loop/
Share on other sites

There's no need to first select the number of fonts, then select each font individually.  Just select all the fonts at once and loop the results.

 

$sql = 'SELECT * FROM fonts';
$res = mysql_query($query);
echo '<select>';
while ($row=mysql_fetch_array($res)){
   if ($row['id'] == $font){ $selected='selected="selected"'; }
   else { $selected=''; }

   echo '<option value="'.$row['id'].'" '.$selected.'>'.$row['font'].'</option>';
}
echo '</select>';

 

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.