techno surprises

January 23, 2008

PHP – MSSQL to XML

Filed under: code, column, connect, connection string, mssql, name, php, php mssql, row, sample, software, xml — Mustafa Turan @ 4:04 pm

These piece of PHP code is help to understand;

  • How to get column names from MSSQL with PHP?
  • How to get related row attributes from MSSQL with PHP?
  • And how to convert MSSQL tables to XML data store type?

Here is the source code, it is completely free and usable for any purposes.

<?php

// Coder Mustafa Turan

// https://mustafaturan.wordpress.com/
// get query from URL
$query    = urldecode($_GET[‘q’]);
if(empty($_GET[‘q’])) exit();
echo “<?xml version=\”1.0\” encoding=\”UTF-8\”?>”;
    /*
    sample query:
    $query = “SELECT * FROM table_name”;
    */

    // connection open to MSSQL
    $link = mssql_connect(‘hostname’, ‘username’, ‘password’);
    mssql_select_db(‘dbname’, $link);

    // get the query result
    $result = mssql_query($query, $link);
    $i = 0;

    // get all columns readed from query
    while ($column = mssql_fetch_field ($result)){
        $columnx[$i] = $column->name;
        $i++;
    }
    $column = null;

    // read all rows with its column name
    while (($row = mssql_fetch_array($result, MSSQL_BOTH)))
    {
        echo “\n <new_row>”;
        foreach($columnx as $C){
            // $C                : column name
            // $row[$C]            : it give the current rows’ column variable
            // sample output    : <column_name>column_content</column_name>
            echo “\n  <” . $C . “>” . $row[$C] . “</” . $C . “>”;
        }
        echo “\n </new_row>”;
    }

    // close the current connection
    mssql_free_result($result);
    mssql_close($link);
echo “\n</xml>”;
?>

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.