1

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.

2
  • Are you only selecting one row? The ternary operator is currently part of the string. Commented Feb 10, 2016 at 4:00
  • yes,here when the status is 1 the enable will selected otherwise disable. Commented Feb 10, 2016 at 4:03

1 Answer 1

1

** 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>
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. As chris85 mentioned, you should switch your mysql_ statements to mysqli (or PDO) as mysql is depreciated and future support for it is not guaranteed. It will also be more secure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.