[英]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中使用它
$.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);
?>
<?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);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.