Select Option ERROR

Discussion in 'PHP' started by badmasketa, May 21, 2008.

  1. #1
    Take a look at this code, whats wrong with this? i just wanna call that list of select menu from a table, that code does but only displays the last row
    i wanna display all the rows from that table.........

    <?
    include 'connect.php';
    $result = mysql_query('SELECT * FROM ev_category order by cat_id desc'); 
    while($row = mysql_fetch_array($result)) { 
    $a=$row[0];
    $b=$row[1];
    }
    ?>
    
    Select Category
    <?
    echo "<select name=\"category\">
    <option value=\"$a\" selected=\"selected\">$b</option>
    </select>";
    ?>
    Code (markup):
     
    badmasketa, May 21, 2008 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You will need to loop through the results. The selected="selected" isn't going to work the way you want it to here. You will need to use an if statement to get the correct value to be selected.

    
    <?php
    include 'connect.php';
    ?>
    
    Select Category
    <select name="category">
    
    <?php
    $result = mysql_query('SELECT * FROM ev_category order by cat_id desc');
    
    while($row = mysql_fetch_array($result)) { 
    echo '<option value="'.$row[0].'" selected="selected">'.$row[1].'</option>';
    }
    ?>
    
    </select>
    
    PHP:
     
    jestep, May 21, 2008 IP
  3. badmasketa

    badmasketa Well-Known Member

    Messages:
    351
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    103
    #3
    yeah thanks for that and if you dont mind can you please give me the suggestions how can i get to that for "selected" using if statement... that will be great ....
     
    badmasketa, May 21, 2008 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    I'm not sure what criteria you are using to pre-select something but something like this:

    
    while($row = mysql_fetch_array($result)) 
    {
    if($row[0] == $some_criteria)
    {
    echo '<option value="'.$row[0].'" selected="selected">'.$row[1].'</option>';
    } else {
    echo '<option value="'.$row[0].'">'.$row[1].'</option>';
    }
    }
    
    PHP:
     
    jestep, May 21, 2008 IP
  5. badmasketa

    badmasketa Well-Known Member

    Messages:
    351
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    103
    #5
    Thanks Jestep for your kind support..... ;)
     
    badmasketa, May 23, 2008 IP