简体   繁体   中英

Using pivottable.js with PHP query on Sql Server

I want to use pivottable.js on my data which I pulled from SQL Server using php. Examples( http://nicolas.kruchten.com/pivottable/examples/ ) are for files JSON and CSV. My data connection to html page is like below. How can I directly use this data on pivottable.js?

$server = "SQLSERVER";
$connectionInfo=array("Database"=>"SQLDATABASE","CharacterSet" => "UTF-8");
$conn= sqlsrv_connect($server,$connectionInfo);

$sql ="SELECT Column1,Column2,Column3,Column4 from TABLE";
$stmt = sqlsrv_prepare( $conn, $sql, array(), array('Scrollable' =>'buffered'));
if( $stmt === false ) {
  die( print_r( sqlsrv_errors(), true));
 }
 sqlsrv_execute($stmt);
while($row = sqlsrv_fetch_array($stmt))
{
 echo "<li>" . $row["Column1"] . $row["Column2"] . "</li>";
}
 echo "<table border=1><tr><th>HEAD1</th><th>HEAD2</th><th>HEAD3</th><th>HEAD4</th></tr>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC)) 
{
    echo "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td>     <td>".number_format($row[3], 0, ',', '.')."</td></tr>";
}
echo "</table>";
sqlsrv_free_stmt( $stmt);  
sqlsrv_close( $conn);  

You could generate JSON array. It should look like

[
["HEAD1", "HEAD2", "HEAD3", "HEAD4"],
["va1", "val2", "val3", 123.45],
...
]

On page you may query PHP via $.ajax and then use pivottable.js with the result. $ajax is conviniet to show 'waiting' gif and hide it in 'success' finction.

    $.ajax({
        type: 'post',
        url: 'https://path_to_your_php_script',
        data: {
            param1: "value1",
            param2: "value2",
            ...
        },
        success: function (response) {
            $("#output").pivotUI(eval(response), {
                    rows: ["HEAD1", "HEAD2"],
                    cols: ["HEAD3"],
                    vals: ["HEAD4"]
            });
        }   
    });

Other way

    $.getJSON("https://path_to_your_php_script", function(mps) {
        $("#output").pivotUI(mps, {
                    rows: ["HEAD1", "HEAD2"],
                    cols: ["HEAD3"],
                    vals: ["HEAD4"]
            });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM