简体   繁体   中英

Corresponding ID is not shown as “selected” result in dropdown

I've got a php page which will show a form. In the form you need to select a driver. Drivers are selected from a mysql db, that part works just fine. However, I would like to see that the user that is logged in, automatically is selected as default driver for this form.

What am I missing? Any help is greatly apprciated!

mysqli_set_charset($connection, 'utf8');

$query  = "SELECT name, substring_index(substring_index(mrb_users.user_qualified,'|',-2),'|',1) as driver, id  ";
$query .= "from mrb_users having driver like 'B%' ORDER BY name ";
$sql = mysqli_query($connection, $query);

$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option value='". $row['id'] ."' if('".$row['id']."'==='".$_SESSION['id']."') 'selected'>" .$row['name'] . ' - ' .$row['chauffeur'] ."</option>" ;
}

$conn->close();

It looks like the PHP if statement is included in double quotes and therefore printed verbatim. If so, you should be able to see it using your browser's HTML inspector.

For clarity, I recommend (1) factoring out the if statement to a separate line and (2) using sprintf() instead of concatenating a large number of strings:

$sel = ($row['id'] === $_SESSION['id'])
  ? 'selected'
  : '';
sprintf('<option value="%s" %s>%s - %s</option>',
        $row['id'], $sel, $row['name'], $row['chauffeur']);

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