从数据库中提供选择列表

时间:2016-02-15 05:06:41

标签: php sql-server database selectlist

我正在尝试填充数据库中的选择列表。我只想要专栏' blogID'填写它,然而我得到10个不同的选择列表,所有人都说"选择一个"。我真的不确定如何解决它。

<?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); ?>
我在做错了什么?尝试了严厉的不同方法,但这就像我得到的那样接近......

2 个答案:

答案 0 :(得分:3)

因为您在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中使用短标签

答案 1 :(得分:2)

只需在循环外移动<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); ?>