Using PHP to query a MDB file, and return JSON

前端 未结 4 1115
你的背包
你的背包 2021-01-25 07:46

I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make m

4条回答
  •  抹茶落季
    2021-01-25 08:22

    I use this code to get results from an ODBC query into a JSON array:

    $response = null;
    $conn = null;
    
    try {
      $odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
    
      $sql_query = "SELECT * FROM table;";
    
      $conn = odbc_connect($odbc_name, 'user', 'pass');
      $result = odbc_exec($conn, $sql_query);
    
      //this will show all results:
      //echo odbc_result_all($result);
    
      //this will fetch row by row and allows to change column name, format, etc:     
      while( $row = odbc_fetch_array($result) ) { 
         $json['cod_sistema'] = $row['cod_sistema'];
         $json['sistema'] = $row['sistema'];
         $json['cod_subsistema'] = $row['cod_subsistema'];
         $json['sub_sistema'] = $row['sub_sistema'];
         $json['cod_funcion'] = $row['cod_funcion'];
         $json['funcion'] = $row['funcion'];
         $json['func_desc_abrev'] = $row['desc_abreviada'];
         $json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
    
         $response[] = array('funcionalidad' => $json);
      }
    
      odbc_free_result($result); //<- Release used resources
    
    } catch (Exception $e) {
       $response = array('resultado' => 'err', 'detalle' => $e->getMessage());
       echo 'ERROR: ',  $e->getMessage(), "\n";
    }
    odbc_close($conn);
    return $response;
    

    And finnally encoding the response in JSON format:

    echo json_encode($response);
    

提交回复
热议问题