简体   繁体   中英

How to display database value inside select tag using PHP and MySQL

I need one help .I can not display some db values inside select tag using PHP and MySQL.I am explaining my code below.

<?php
    while($row=mysql_fetch_array($sql)){
    if($row['status']==1){
         $status=1;
     }else{
     $status=0; 
    }
    $id=$row['id'];
    echo "<tr>
     <td>".$counter++."</td>
     <td>".$row['pincode']."</td>
    <td>".$row['area']."</td>
    <td>
    <select class='form-control' id='status' name='status' onchange='javascript:adminstatus()' style='height:23px; padding:0px;'>
         <option value=''>Select Status</option>
        <option value='1'  ".$row['status']."=='1'?'selected':'';>Enable</option>
     <option value='0'  ".$row['status']."=='0'?'selected':'';>Disable</option>
    </select>
    </td>
    ?>

Here I need when $status==1 the enable will select and $status==0 disable will select.Please help me.

** UPDATE ** Correction I would take your statements out of an echo and just use the echo for the php values. It will be easier to read and maintain. For example:

<td><?php echo $counter++ ?></td>

Then I would write the logic part like so

<option value='1' <?php echo ($row['status']=='1'? 'selected' : '') ?>>Enable</option>
<option value='0' <?php echo ($row['status']=='0'? 'selected' : '') ?>>Disable</option>

However, if you want to write the code the way you have...

$id=$row['id'];
echo "<tr>
 <td>".$counter++."</td>
 <td>".$row['pincode']."</td>
<td>".$row['area']."</td>
<td>
<select class='form-control' id='status' name='status' onchange='javascript:adminstatus()' style='height:23px; padding:0px;'>
     <option value=''>Select Status</option>
    <option value='1' " . ($row['status']=='1'?'selected':'') . ">Enable</option>
 <option value='0' " . ($row['status']=='0'?'selected':'') . ">Disable</option>
</select>
</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM