PHP Drop down list using MS SQL DB

Hi Guys

I am having problems loading my drop down list with data from a MS SQL database

Please help!

[php]
$sql=“SELECT UserID, UserName FROM users”;
$result=sqlsrv_query($sql);

$options="";

while ($row=sqlsrv_fetch_array($result)) {

$userid=$row["UserID"];
$username=$row["UserName"];
//$options.="<OPTION VALUE=\"$userid\">".$username;
$options.="<option value='".$row["UserID"]."'>".$row["UserName"]."</option>\n";

}
[/php]

<select name=username style="margin-left:250px;">
<option value=-1>Choose User
<?=$options?>
</select>

if may be your server is not setup to use short tags try:

[php]<?php echo $options;?>[/php]

Hi Cillie Vlotman,

I’m not familiar with ms sql database so i have to assume whatever sqlsrv that you are using is correct. The only problem i see in your code is the missing closing option tag.

Choose User[b][/b]

Regards,
developer.dex2908

<?= is the samething as doing <?php echo. I'm not seeing any version information on sqlsvr, unless you really have to use it, i'd try the standard mysql_query() and mysql_fetch_arry(). try [php] <?php $result=mysql_query("SELECT UserID, UserName FROM users") or die(mysql_error()); ?> Choose User <?php while ($row=mysql_fetch_array($result)) { echo "$row[UserName]\n"; } ?> [/php]

I know that method works, i use it in several of my own projects.

Agreed but not all servers are setup to use short tags,

Thanks for the reply. I have tried all the suggestions but still nothing. To add to this, I was using a mysql db and the code as it is above was working fine but since I moved to SQL db I had the problems. The sqlsrv statement works fine elsewhere in the program just not with the drop downs?

Thanks all, I managed to get it working by changing two parts of code:

In the php code I added the connection variable ($conn) to the sqlsrv_query

[php]
$sql=“SELECT UserID, UserName FROM users”;
$result=sqlsrv_query($conn,$sql);

$options="";

while ($row=sqlsrv_fetch_array($result)) {

$userid=$row["UserID"];
$username=$row["UserName"];
$options.="<OPTION VALUE=\"$userid\">".$username;
//$options.="<option value='".$row["UserID"]."'>".$row["UserName"]."</option>\n";

}
[/php]

and in the html part I used the suggestion by ‘daveismyname’ :

<select name=username style="margin-left:250px;">
<option value=-1>Choose User
<?php echo $options;?>
</select>
Sponsor our Newsletter | Privacy Policy | Terms of Service