Search code examples
phpmenuselected

PHP List Menu Boxes - Best way to do the cycle?


This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )

// first query to get cats from user table

$query = "select * from user where name='".$_SESSION['username']."' order by id ASC  limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){


$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];

}
}

// now i want to build 10 select boxes with selected according the user table $cats

// below is what i can build to first box $cat1

// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code

<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {

if ( $cat1 == $row['id'] ) { 

print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";

}

else {

print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";

}


}
?>
</select>

I am not a coder so this might not be effective code.

Hope someone can help me here and understands what i am trying to do.

Many Thanks.


Solution

    • The code is fine. This 10 cycles as you name it is a almost zero cost.

    • This is the usual way we do it, we fetch sequentialy the records one by one.

    • In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.

    • On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.

      for($i=0;$i<99999;$i++)
          (9999*9999);
      
      echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
      

      ?>