Page 1 of 1

Problems with extracting information

Posted: Mon Nov 17, 2008 2:14 pm
by c0mrade
Hi all,

Code: Select all

 
<select name="comp" id="comp" style="width:130px;">
    <?php $sqlcomp = mysql_query("SELECT * FROM comp");
      while ($redcomp = mysql_fetch_array($sqlcomp)) {
      extract($redcomp);
         echo "<option value=\"$comp_id\">comp_name</option>";
    
    }
    ?>
        
                        </select>
 
My question is following, I have $_SESSION['comp_id'] equals some value, now I'd like to make 1st option in the list the one I'm having stored in session.

Ex :

Results from database are :
comp_id comp_name
1 comp1
2 comp2
3 comp3

and in session I have stored $_SESSION['comp_id'] equals 2 ; now I'd like to get the following result in html from php :

Code: Select all

 
<select name="comp" id="comp" style="width:130px;">
<option value="2">comp2</option>
<option value="1">comp1</option>
<option value="3">comp3</option>
</select>
 
OR

Code: Select all

 
<select name="comp" id="comp" style="width:130px;">
<option value="2">comp2</option>
<option value="3">comp1</option>
<option value="1">comp3</option>
</select>
 
it really doesn't matter as long as item from session is located 1st on the list. Thank you and I apologize for my bad English.

Re: Problems with extracting information

Posted: Mon Nov 17, 2008 2:27 pm
by requinix
Put the one you want to use as the first value (do it manually), then change your query to select everything that isn't that value.

Re: Problems with extracting information

Posted: Mon Nov 17, 2008 4:10 pm
by Yossarian
Most people would be happy to make the matched one from the session be pre-selected.

Code: Select all

 
  <select name="comp" id="comp" style="width:130px;">
 
<?php $sqlcomp = mysql_query("SELECT * FROM comp");
 
       while ($redcomp = mysql_fetch_array($sqlcomp)) {
       extract($redcomp);
        if( $_SESSION['comp_id'] == $comp_id ){
        echo "<option value=\"$comp_id\" selected = \"selected\">comp_name</option>";
         }else{
          echo "<option value=\"$comp_id\">comp_name</option>";
         }
     }
?>
</select>
 
Though you can do the same thing with far less code if you wish.