在php表中显示MSSQL选择数据

时间:2011-12-30 20:49:37

标签: php sql-server-2005

我很遗憾,我很遗憾。这是我第一次从MSSQL服务器提取数据并使用php在表中显示它。我以前用mysql做过这个,但是不能让它与mssql一起工作。这是我目前的代码:

<?php
 $myServer = "server";
 $myUser = "user";
 $myPass = "password";
 $myDB = "mssqldb"; 

 //connection to the database
 $dbhandle = mssql_connect($myServer, $myUser, $myPass)
     or die("Couldn't connect to SQL Server on $myServer"); 

 //select a database to work with
      $selected = mssql_select_db($myDB, $dbhandle)
          or die("Couldn't open database $myDB"); 

 //declare the SQL statement that will query the database
     $query = "SELECT col1, col2 ";
     $query .= "FROM sqltable ";

 //execute the SQL query and return records
     $result = mssql_query($query)
         or die('A error occured: ' . mysql_error());

 //Show results in table

 $o = '<table id="myTable">
         <thead>
         <tr>
         <th>Col 1</th>
         <th>Col 2</th>
         </tr>
         </thead><tbody>';

      while ( $record = mssql_fetch_array($result) )
          {
              $o .= '<tr><td>'.$col1.'</td><td>'.$col2.'</td></tr>';
          }               

       $o .= '</tbody></table>';

       echo $o;

    //Show result from sql table separated by comma (commented out)
       /* while ( $record = mssql_fetch_array($result) )
        {
            echo $record["col1"] . " , " . $record["col2"] . "<br />";
        } */

    //free result set memory
        mssql_free_result($result);

    //close the connection
        mssql_close($dbhandle);
    ?>

2 个答案:

答案 0 :(得分:4)

永远不会定义$ col1和$ col2变量。您应该使用注释部分中的内容,$ record [“colname”]。

答案 1 :(得分:3)

while ( $record = mssql_fetch_array($result) )
          {
              $o .= '<tr><td>'.$record ['col1'].'</td><td>'.$record ['col2'].'</td></tr>';
          }