如何处理 PHP 中的查询数据

How to process data from query in PHP

我想在我的 html 页面中显示来自 SQL 服务器数据库的数据。我已经写了一个获取数据的代码 PHP :

<?php 
      $serverName = "srv\SQLEXPRESS";
      $connectionInfo = array("Database" => "PROFACE", "UID"=>"username", "PWD"=>"pwd");
      $conn = sqlsrv_connect($serverName, $connectionInfo);

      if($conn) {
        echo "Connexion OK <br/>";
      } else {
        echo "La connexion NOK <br/>";
        die(print_r(sqlsrv_errors(), true));
      }

      $sql = "SELECT * 
              FROM PROFACE.dbo.SuiviProduction 
              WHERE Time_Stamp >= DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()),0)
              AND DATEPART(HOUR,Time_Stamp) = DATEPART(HOUR,GETDATE())-2";

      $params = array(1, "some data");
      $stmt = sqlsrv_query($conn, $sql, $params);
      if($stmt == false) {
        die(print_r(sqlsrv_errors(), true));
      } else {
        $data = sqlsrv_fetch_array($stmt);
        sqlsrv_free_stmt($stmt);
        sqlsrv_close($stmt);
      }
     ?>

然后我想显示查询的结果,所以我写了:

foreach ($data as $key => $value) {
         //echo "{$key} => {$value}";
          print_r($data);
}

我有以下内容:

Array ( [0] => DateTime Object ( [date] => 2019-11-13 08:00:00 [timezone_type] => 3 [timezone] => Europe/Paris ) [Time_Stamp] => DateTime Object ( [date] => 2019-11-13 08:00:00 [timezone_type] => 3 [timezone] => Europe/Paris ) [1] => 237 [Time_Stamp_ms] => 237 [2] => 2227 [CompteurTotalLot] => 2227 [3] => 2001 [CompteurBonnesLot] => 2001 [4] => 10 [CompteurRebutsLot] => 10 [5] => 3120227 [CompteurTotalisateur] => 3120227 )

如何处理这些数据才能获得 json 格式的数据?

您需要考虑以下几点:

  • 使用 sqlsrv_fetch_array()SQLSRV_FETCH_ASSOCSQLSRV_FETCH_NUMERIC 作为 $fetchType 参数,每列只检索一个值(默认值为 SQLSRV_FETCH_BOTH
  • PHP SQL 服务器的驱动程序可以 return PHP DateTime 对象作为字符串或通过在连接字符串中设置 'ReturnDatesAsStrings' 选项作为 DateTime 对象或者在语句级别(默认值为 false)。如果您想要文本输出,请在 sqlsrv_query() 中使用此选项调用或使用 PHP DateTime::format() 方法格式化您的 PHP DateTime 对象。
  • 使用sqlsrv_close()关闭连接,而不是语句。

下一个示例可能有助于获得预期结果:

JSON 满:

<?php 
    // Connection
    $serverName = "srv\SQLEXPRESS";
    $connectionInfo = array("Database" => "PROFACE", "UID"=>"username", "PWD"=>"pwd");
    $conn = sqlsrv_connect($serverName, $connectionInfo);
    if ($conn) {
        echo "Connexion OK <br/>";
    } else {
        echo "La connexion NOK <br/>";
        die(print_r(sqlsrv_errors(), true));
    }

    // Statement
    $sql = "
        SELECT * 
        FROM PROFACE.dbo.SuiviProduction 
        WHERE 
            Time_Stamp >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0) AND 
            DATEPART(HOUR, Time_Stamp) = DATEPART(HOUR, GETDATE()) - 2
    ";
    $params = array(1, "some data");
    $stmt = sqlsrv_query($conn, $sql, $params);
    if ($stmt === false) {
        die(print_r(sqlsrv_errors(), true));
    }

    // JSON Output
    $output = array();
    while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $output[] = $row;
    }
    file_put_contents('filename.txt', json_encode($output));

    // End
    sqlsrv_free_stmt($stmt);
    sqlsrv_close($conn);
?>

HTML 输出:

<?php 
    // Connection
    $serverName = "srv\SQLEXPRESS";
    $connectionInfo = array("Database" => "PROFACE", "UID"=>"username", "PWD"=>"pwd");
    $conn = sqlsrv_connect($serverName, $connectionInfo);
    if ($conn) {
        echo "Connexion OK <br/>";
    } else {
        echo "La connexion NOK <br/>";
        die(print_r(sqlsrv_errors(), true));
    }

    // Statement
    $sql = "
        SELECT * 
        FROM PROFACE.dbo.SuiviProduction 
        WHERE 
            Time_Stamp >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0) AND 
            DATEPART(HOUR, Time_Stamp) = DATEPART(HOUR, GETDATE()) - 2
    ";
    $params = array(1, "some data");
    $options = array('ReturnDatesAsStrings' => true);
    $stmt = sqlsrv_query($conn, $sql, $params, $options);
    if ($stmt === false) {
        die(print_r(sqlsrv_errors(), true));
    }

    // HTML output
    echo '<table>';
    while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        echo '<tr>';
        foreach ($row as $value) {
            echo '<td>'.$value.'</td>';
        }   
        echo '</tr>';
    }
    echo '</table>';

    // End
    sqlsrv_free_stmt($stmt);
    sqlsrv_close($conn);
?>