【问题标题】:Output a JSON in PHP generated on SQL SERVER with JSON AUTO使用 JSON AUTO 输出在 SQL SERVER 上生成的 PHP 中的 JSON
【发布时间】:2020-09-22 12:42:22
【问题描述】:

我正在尝试通过命令FOR JSON AUTO 在 SQL SERVER 上获取 JSON 格式的输出 我需要在 SQL SERVER 上用 PHP 执行查询,然后将其输出为合法的 JSON。 我应该如何进行? 我通常使用下面的代码来生成 JSON,但是如果我需要获取 JSON 怎么办?

$key= $_GET['key'];
$date=$_GET['date'];
$brand=$_GET['brand'];
    if ($key=="...")
{

    $serverName = "XXX,YYYY"; // \\MSSQLSERVER";
    $connectionOptions = [
    "Database" => "db",
    "UID" => "user",
    "PWD" => 'xxxx'
    ];

    $conn = sqlsrv_connect($serverName, $connectionOptions);
    if ($conn === false) {
        die(formatErrors(sqlsrv_errors()));
    }
            $tsql = "select * from admin_all.Datafeed FOR JSON AUTO;";


    // Executes the query
    $stmt = sqlsrv_query($conn, $tsql);
            // Error handling
    if ($stmt === false) {
        die(formatErrors(sqlsrv_errors()));
    }
    

    $array = array();
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {



        $array[]=$row;
    }
    echo json_encode(array("data"=>array_values($array)));

    sqlsrv_free_stmt($stmt);
    sqlsrv_close($conn);
}

【问题讨论】:

    标签: php json sql-server sqlsrv


    【解决方案1】:

    意外结果的原因是不需要json_encode() 调用(但它始终是一个选项)。 FOR JSON AUTO 返回一个有效的 JSON,所以你只需要回显生成的 JSON。请注意,如果您想将单个顶级元素添加到 FOR JSON 子句的 JSON 输出,则需要使用 ROOT 选项。

    示例,基于您的尝试:

    <?php
    ...
    $json = '';
    if ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH)) {
       $json = $row[0];
    }
    echo '{"data":'.$json.'}';
    ...
    ?>
    

    json_encode() 为例:

    <?php
    ...
    
    $sql = "SELECT id FROM (VALUES (1), (2)) v(id)";
    $stmt = sqlsrv_query($conn, $sql);
    if($stmt == false){
        die( print_r( sqlsrv_errors(), true) );
    }
    
    $json = array();
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $json[] = $row;
    }
    echo json_encode(array("data" => array_values($json)));
    
    ...
    ?>
    

    FOR JSON AUTOROOT 选项的示例:

    <?php
    ...
    
    $sql = "SELECT id FROM (VALUES (1), (2)) v(id) FOR JSON AUTO, ROOT('data')";
    $stmt = sqlsrv_query($conn, $sql);
    if($stmt == false){
        die( print_r( sqlsrv_errors(), true) );
    }
    
    $json = '';
    if ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
        $json = $row[0];
    }
    echo $json;
    
    ...
    ?>
    

    生成的 JSON:

    {"data":[{"id":1},{"id":2}]}
    

    【讨论】:

      【解决方案2】:

      PHP 示例;

       // This file is to be called by AJAX
       <?php
       require_once('db.php');
       $select = mysqli_query($con, "select * from table where index='something'");
       $row[]=mysqli_fetch_array($select);
       echo json_encode($row);
       ?>
      

      JS 示例(获取上面的 PHP) *注意:这里使用 jQuery 3.4.1

       $(document).ready(function() {
       $.ajax({
      
       url:"myserverfile.php",
       method:"POST",
       dataType:"json",
      
       success:function(response) { // Doesn't have to be called response, can be anything
       var a=(response[0]['indexone']); // A name of an index from the sql row you are retrieving
       var b=(response[0]['indextwo']);  // A name of an index from the sql row you are retrieving
       var c=(response[0]['indexthree']);  // A name of an index from the sql row you are retrieving
      
       // Check to see values
       console.log(a);
       console.log(b);
       console.log(c);
       }
      
       });
       });
      

      在具有实时数据库的工作服务器上测试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多