从SQL表中选择数据并将其转换为json formate?

时间:2017-02-06 13:23:41

标签: jquery sql-server json

我是新手使用SQL Server。我尝试从SQL Server表中获取数据并将其转换为JSON格式并在HTML表中显示。我试着做这两件事。但仍然无法取得成功。如果有人知道怎么做,请帮助我。感谢您的任何帮助。

这是我的T-SQL查询。

function Crawled_sites_total(){
//$sql = "SELECT * FROM crawl_site";
$sql = "SELECT  
    CSCH.CrawlSiteID, CSCH.CrawlHistoryID, CSCH.CountAtStart, 
    CSCH.CountAtEnd, CSCH.RecodsFound, CSAR.CrawlSite, 
    CSAR.AverageRecords as Standered, 
    CAST((((CONVERT(FLOAT, CSCH.RecodsFound) - CONVERT(FLOAT, CSAR.AverageRecords)) * 2 * 100) / (CONVERT(FLOAT, CSAR.AverageRecords) + CONVERT(FLOAT, CSCH.RecodsFound))) AS DECIMAL(18, 2)) as Tolerance 
FROM 
    csCrawlSiteCrawledHistory as CSCH 
INNER JOIN 
    csCrawledHistory as CH on CSCH.CrawlHistoryID = CH.CrawlHistoryID 
INNER JOIN 
    csCrawlSiteAverageRecords as CSAR on csch.CrawlSiteID = CSAR.CrawlSiteId 
WHERE 
    CH.CrawlHistoryID = (SELECT TOP 1 C.CrawlHistoryID 
                         FROM csCrawledHistory C 
                         WHERE C.EndTime IS NOT NULL 
                         ORDER BY C.EndTime DESC) ";
//$result = $GLOBALS['conn']->query($sql);
while($row = mssql_fetch_assoc($sql)){

    $row = array(
        // data from theme
        //'id'      => $row['id'],
        'CrawlSiteID'       => $row['CrawlSiteID'],
        'CrawlHistoryID'    => $row['CrawlHistoryID'],
        'CountAtStart'  => $row['CountAtStart'],
        'CountAtEnd'    => $row['CountAtEnd'],
        'RecodsFound'   => $row['RecodsFound'],
        'CrawlSite' => $row['CrawlSite'],
        'Standered' => $row['Standered'],
        'Tolerance' => $row['Tolerance'],
    );
    $data[] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $row);
}  
echo  json_encode($data);

}

1 个答案:

答案 0 :(得分:1)

希望这会对你有所帮助

MIME::Parser

结果:

SELECT name, surname FROM emp FOR JSON AUTO