Problems with extracting information

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
c0mrade
Forum Newbie
Posts: 19
Joined: Mon Oct 06, 2008 4:17 am

Problems with extracting information

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Problems with extracting information

Post 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.
Yossarian
Forum Contributor
Posts: 101
Joined: Fri Jun 30, 2006 4:43 am

Re: Problems with extracting information

Post 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.
Post Reply