从数据库中提供选择列表

Feeding selectlist from database

我正在尝试从我的数据库中填充一个选择列表。我只想要 'blogID' 列来填充它,但是我得到 10 个不同的选择列表,都说 "choose one"。我不太确定如何解决它。

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$serverName = "localhost"; 
$uid = "*****";   
$pwd = "*****";  
$databaseName = "blog"; 

$connectionInfo = array( "UID"=>$uid,                            
"PWD"=>$pwd,                            
"Database"=>$databaseName); 
$con=sqlsrv_connect( $serverName, $connectionInfo);
if ($con)
{
} else {
die( print_r(sqlsrv_errors(), true));
}
$result = sqlsrv_query($con,"SELECT TOP 10 * FROM blog_posts ORDER BY blogID DESC");
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_BOTH)) 
{ 
?>
<select>
<option selected="selected">Choose one</option>
 <?php
foreach($row['blogID'] as $name) { ?>
  <option><?= $name['name'] ?></option>
 <?php
} ?>
</select> 

<?php } sqlsrv_close($con); ?>

我做错了什么?尝试了多种不同的方法,但这与我得到的一样接近..

因为您在 while 循环中使用 <select>

试试这个:

    <?php
    error_reporting(E_ALL); ini_set('display_errors', 1);
    $serverName = "localhost"; 
    $uid = "*****";   
    $pwd = "*****";  
    $databaseName = "blog"; 

    $connectionInfo = array( "UID"=>$uid,                            
    "PWD"=>$pwd,                            
    "Database"=>$databaseName); 
    $con=sqlsrv_connect( $serverName, $connectionInfo);
    if ($con)
    {
    } else {
    die( print_r(sqlsrv_errors(), true));
    }
    $result = sqlsrv_query($con,"SELECT TOP 10 * FROM blog_posts ORDER BY blogID DESC");
    ?>
    <select>
    <option selected="selected">Choose one</option>
    <?php
    while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_BOTH)) 
    { 
    ?>
      <option><?= $row['blogID'] ?></option>
    <?php } 
    ?>
    </select> 
    <?php
    sqlsrv_close($con); ?>

请不要在PHP

中使用短标签

只需将 <select> 标签和 choose one 选项移出循环,不需要 foreach 循环。这是您的代码的正确方法。

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$serverName = "localhost"; 
$uid = "*****";   
$pwd = "*****";  
$databaseName = "blog"; 

$connectionInfo = array( "UID"=>$uid,                            
"PWD"=>$pwd,                            
"Database"=>$databaseName); 
$con=sqlsrv_connect( $serverName, $connectionInfo);
if ($con)
{
} else {
die( print_r(sqlsrv_errors(), true));
}
$result = sqlsrv_query($con,"SELECT TOP 10 * FROM blog_posts ORDER BY blogID DESC");
?>
<select>
<option selected="selected">Choose one</option>
<?php
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_BOTH)) 
{ 
?>
<option><?= $row['name'] ?></option>
<?php 
} 
?>
</select> 
<?php
sqlsrv_close($con); ?>