techno
techno

Reputation: 6500

Selecting a value from select using php

I have a select input i need populate it from a db and select the value that matches a variable product. I have

while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
 echo "<option value='".$row['pname']."'>".$row['pname']."<?php
 if($row['pname']==$product) echo 'selected'</option>";

Select Entries are populated from pname and the option with name that equals $product should be selected. Im getting this error syntax error,

unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in

Upvotes: 1

Views: 28

Answers (2)

cyber_rookie
cyber_rookie

Reputation: 665

Try this

while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
   echo "<option value='".$row['pname']."' ";
   if($row['pname']==$product) echo 'selected';
   echo ">".$row['pname']."</option>";
}

Upvotes: 1

prava
prava

Reputation: 3986

Check this one -

while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
    $selected = '';

    if ($row['pname'] == $product) {
        $selected = 'selected';
    }

    echo '<option value="' . $row['pname'] . '" ' . $selected . '>' . $row['pname'] . '</option>';
}

Upvotes: 1

Related Questions