将Ms Ms数据存储到javascript数据集中

时间:2014-04-04 03:46:03

标签: javascript php ms-access

我有一个代码可以获取php及其工作中的MS Access数据库中的所有数据。

$conn = odbc_connect('pivot_test','','') or die ("Error in connection");
$sql = "select * from empDetails"; 
$rs = odbc_exec($conn,$sql);
if (!$rs)
   { exit ("Error in Sql");}
    echo "<table><tr>";
    echo "<th>id</th>";
    echo "<th>year</th>";
    echo "<th>month</th>";
    echo "<th>empName</th>";
    echo "<th>empPos</th>";
    echo "<th>numMc</th>";
    echo "<th>numLeave</th></tr>";
    while (odbc_fetch_row($rs))
    {
    $id = odbc_result($rs,"id");
    $year = odbc_result($rs,"year");
    $month = odbc_result($rs,"month");
    $empName = odbc_result($rs,"empName");
    $empPose = odbc_result($rs,"empPos");
    $numMc = odbc_result($rs,"numMc");
    $numLeave = odbc_result($rs,"numLeave");
    }
    odbc_close($conn);
    echo"</table>";
    ?>

但现在我需要在数据集中存储所有数据:

var pivot_dataset = [
{"id": 1, "year": 2014 , "month": "JAN", "empName": "David", "empPos": "engineer", "numMc": 1, "numLeave": 2},
];

怎么做?请告知。

1 个答案:

答案 0 :(得分:1)

查看json_encode方法。如果您传递一个关联数组,它将返回一个JSON字符串。

<?php

$conn = odbc_connect('pivot_test','','') or die ("Error in connection");
$sql = "select * from empDetails"; 
$rs = odbc_exec($conn, $sql);

if (!$rs)
   exit ("Error in Sql");

echo "<table><tr>";
echo "<th>id</th>";
echo "<th>year</th>";
echo "<th>month</th>";
echo "<th>empName</th>";
echo "<th>empPos</th>";
echo "<th>numMc</th>";
echo "<th>numLeave</th></tr>";

$pivot_dataset = array();
while(odbc_fetch_row($rs)) {
    // Push this data onto the end of the array
    $pivot_dataset[] = array(
        'id' => odbc_result($rs,"id"),
        'year' => odbc_result($rs,"year"),
        'month' => odbc_result($rs,"month"),
        'empName' => odbc_result($rs,"empName"),
        'empPose' => odbc_result($rs,"empPos"),
        'numMc' => odbc_result($rs,"numMc"),
        'numLeave' => odbc_result($rs,"numLeave")
    );
}

odbc_close($conn);
echo "</table>";

$jsonStr = json_encode($pivot_dataset);

// var pivot_dataset = [{"id": 1, "year": 2014 , "month": "JAN" ... }, { ... }];
echo "var pivot_dataset = $jsonStr;";