简体   繁体   中英

MySQL database connected to a droplist

My code keep showing this:

在此处输入图片说明

instead of showing the database records.

<tr><td>Wie is jou favoriete popgroep? </td>
<td><select>
<?php
$sql="SELECT band,bandid FROM bands order by band"; 


foreach ($result->query($sql) as $row){

echo "<option value=$row[bandID]>$row[band]</option>"; 

}
?>
</select>
</td></tr>

My database:

在此处输入图片说明

Why does it keep saying $row[band] and not the records in my database?

This is an issue with wrong placement of variable in a string definition.

This does not work: echo "<option value=$row[bandID]>$row[band]</option>"; ... Instead use one of these:

echo "<option value=\"" . $row['bandID'] . "\">\"" . $row['band'] . "\"</option>"; 

Or this alternative notation:

echo "<option value=\"{$row['bandID']}\">\"{$row['band']}\"</option>"; 

If things get more complex this might also come in handy:

echo sprintf(
    '<option value="%s">"%s"</option>', 
    $row['bandID'], 
    $row['band']
); 

And in case you are nmot 100% certain about the contents of that array you also need to escape values when inserting them into html markup:

echo sprintf(
    '<option value="%s">"%s"</option>', 
    htmlspecialchars($row['bandID']), 
    htmlspecialchars($row['band'])
); 

尝试:

echo '<option value="'.$row['bandID'].'">'.$row['band'].'</option>';

Use quotes inside foreach, Also replace $conn with your variable

Edited

<tr><td>Wie is jou favoriete popgroep? </td>
<td><select>
<?php
$sql="SELECT Band,BandID FROM bands order by band"; 
$result = $conn->query($sql);

if ($result->num_rows > 0) 
{
    // output data of each row
    while($row = $result->fetch_assoc()) 
    {
        echo "<option value=".$row['BandID'].">".$row['Band']."</option>";
    }
}

?>
</select>
</td></tr>

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