Displaying MS SQL Server Column Names and Values via PHP
Sometimes in a PHP page it may be useful to not only retrieve data values from an MS SQL Server database table, but also to retrieve column names from the table. Listed below is an example of how to do this for MS SQL Server databases using PHP. This example uses MS SQL Server PHP libraries that have been available since PHP 4.
This example makes use of the mssql_num_fields and mssql_fetch_field functions to get a count of the number of columns, and then get the column name for each column index. The mssql_fetch_row function is used to get the values.
<?php
$host = 'localhost';
$port = '1433';
$server = $host . ',' . $port;
$database = 'test';
$user = 'testuser';
$password = 'testpass';
$link = mssql_connect ($server, $user, $password);
if (!$link)
{
die('ERROR: Could not connect: ' . mssql_get_last_message());
}
mssql_select_db($database);
$query = 'select * from employee';
$result = mssql_query($query);
if (!$result)
{
$message = 'ERROR: ' . mssql_get_last_message();
return $message;
}
else
{
$i = 0;
echo '<html><body><table><tr>';
while ($i < mssql_num_fields($result))
{
$meta = mssql_fetch_field($result, $i);
echo '<td>' . $meta->name . '</td>';
$i = $i + 1;
}
echo '</tr>';
while ( ($row = mssql_fetch_row($result)))
{
$count = count($row);
$y = 0;
echo '<tr>';
while ($y < $count)
{
$c_row = current($row);
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '</tr>';
}
mssql_free_result($result);
echo '</table></body></html>';
}
?>