通过php从SQL Server获取数据并将其制成json格式


Getting data from SQL Server thorugh php and making it in json format

我正在尝试制作一个从SQL Server数据库获取数据的UI。我想通过PHP获得它。目前,我可以通过以下代码连接数据库并插入数据

<?php
  
$serverName = "esdapocnv01";
$connectionInfo = array( 'Database'=>'TRG_TEST', 'UID'=>'testuser', 'PWD'=>'Towing@2');
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
	
	echo "Connection could not be established.<br />";
	
}
$class = $_POST['number'];
$teachers=$_POST['teachers1'];
$rooms=$_POST['rooms1'];
$sql = "insert into school(class,teachers,rooms) values ('$class','$teachers','$rooms') ";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo "<option value='" . $row['station'] . "'>" . $row['station'] . "</option>";
                               
}
sqlsrv_free_stmt( $stmt);
?>

现在我想从数据库表中获取数据,并将其转换为JSON格式,以便在UI 中使用它

<?php
    //fetch table rows from mysql db
    $sql = "select * from tbl_employee";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
    $emparray = array();
    while($row =mysqli_fetch_assoc($result)){
       $a['class']=$row['class'];
       $a['teacher']=$row['teachers'];
       $a['room']=$row['rooms'];
       $a['addedat']=Now(); //example of adding extra data if required
       $b[]=$a;
    }
    echo json_encode($b);
?>
$.ajax({
    url: "data1.php", 
    data: {"id": "EMP001"},
    success: function(result){
        var obj = jQuery.parseJSON( result );
        alert( obj.name );
    }
});

data1.php

<?php
    $id=$_REQUEST['id'];
    //fetch table rows from mysql db
    $sql = "SELECT * FROM `tbl_employee` WHERE `id`='$id'";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
    $emparray = array();
    while($row =mysqli_fetch_assoc($result)){
       $emparray[] = $row;
    }
    echo json_encode($emparray);
?>