dimanche 3 juillet 2016

Trying to do a simple SQL table to HTML table example using SQLSRV

Majority of the examples I saw online assume you know the specific column to output. But what if you don't? Here's what I got so far using SQLSRV

            <?php
            $serverName = "serverNameinstanceName";
            $connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
            $conn = sqlsrv_connect( $serverName, $connectionInfo );
            if( $conn === false ) {
                die( print_r( sqlsrv_errors(), true));
            }

            $sql = "SELECT * FROM SomeTable";
            $stmt = sqlsrv_query( $conn, $sql );
            if( $stmt === false) {
                die( print_r( sqlsrv_errors(), true) );
            }

            echo "<table>";
            echo "<thead>";
            echo "<tr>";
            foreach (sqlsrv_fetch_field($stmt) as $column){
                echo "<th>$column</th>";
            }
            echo "</tr></thead>";
            echo "<tbody>";
            echo "<tr>";                
            while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
                echo "<td>$row</td>";
            }
            echo "</tr>";

            echo "</tbody></table>";

            sqlsrv_free_stmt( $stmt);
            ?>

Aucun commentaire:

Enregistrer un commentaire