【问题标题】:Using PHP to query a MDB file, and return JSON使用 PHP 查询 MDB 文件,并返回 JSON
【发布时间】:2013-08-02 15:17:36
【问题描述】:

我有一个 Microsoft Access 数据库,我正在尝试使用 PHP 查询表,并输出有效的 JSON。我有一个 MSSQL 数据库的等效代码,我是否正在尝试让我的代码做同样的事情,但只针对 Access 数据库。

这是 MSSQL 代码

$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));

$sql = "SELECT *
        FROM db.dbo.table";

$data = sqlsrv_query ($conn, $sql);

$result = array();   

do {
    while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
        $result[] = $row;   
    }
} while (sqlsrv_next_result($data));

$json = json_encode ($result);

sqlsrv_free_stmt ($data);
sqlsrv_close ($conn); 

这是我为 MDB 文件尝试的内容

$dbName = "/filename.mdb";

if (!file_exists($dbName)) {
    die("Could not find database file.");
}

$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);

$sql = "SELECT *
        FROM cemetery";

$data = $db->query($sql); // I'm getting an error here
$result = array();   

// Not sure what do do for this part...
do {
    while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
        $result[] = $row;   
    }
} while (sqlsrv_next_result($data));

$json = json_encode ($result);

我有点按照这个尝试连接到数据库:http://phpmaster.com/using-an-access-database-with-php/

目前这给了我一个 500 内部服务器错误。我期待这样的字符串保存在变量$json

[
    {
        "col1":"col value",
        "col2":"col value",
        "col3":"col value",
    },
    {
        "col1":"col value",
        "col2":"col value",
        "col3":"col value",
    },
    {
        etc...
    }
]

有人可以帮我移植上面的 MSSQL 代码,以便我可以将它与 MDB 数据库一起使用吗?感谢您的帮助!


编辑:我正在逐行注释掉这些行,它在$data = $db->query($sql); 行向我抛出了 500 错误。我查看了错误日志,我收到了错误Call to a member function query() on a non-object。我的 php.ini 文件中已经有 extension=php_pdo_odbc.dll 行未注释。有谁知道问题出在哪里?

【问题讨论】:

  • learn 确实使用 echo 进行调试,并找到您的错误所在。我已经找到了一个:while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) 应该是while ($row = $data->fetch(PDO::FETCH_ASSOC))do { .. } while 需要被删除。只要看看你发布的例子,它就在那里
  • 请更新您的问题,告诉我们您预计会发生什么、现在正在发生什么以及您尝试解决的问题。考虑包括您收到的任何错误消息,以及您用于帮助解决问题的资源的描述以及它们如何未能回答您的问题。
  • 当我运行它时,它给了我一个 500 内部服务器错误,所以我看不到任何回显的字符串(即使在进行了您建议的更改后,我也会收到此错误)。我的 MDB 文件与我的站点位于同一目录中,现在也仅用于测试。我已经更新了这个问题,乔治!
  • 查看错误日志,他们通常会有更多关于导致错误/解析错误等的信息。
  • 我已经用错误日志所说的错误更新了问题

标签: php json ms-access


【解决方案1】:

您只需要 1 个循环, fetchAll 是你的可迭代朋友:

while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
    $result[] = $row;   
}

【讨论】:

    【解决方案2】:

    odbc_connect 不返回对象,而是返回资源。见 (http://php.net/manual/en/function.odbc-connect.php) 所以你需要做这样的事情。

     $db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
     $oexec = obdc_exec($db,$sql);
      $result[] = odbc_fetch_array($oexec);
    

    然后你可以迭代结果..

    另见:

    http://www.php.net/manual/en/function.odbc-fetch-array.php http://www.php.net/manual/en/function.odbc-exec.php

    【讨论】:

    • 现在这给了我一个警告 (odbc_fetch_array() expects parameter 1 to be resource, boolean given in C:\\...) 和一个致命错误 (Call to a member function fetchAll() on a non-object in C:\\...)
    • 对不起,我遗漏了错误检查等。您需要检查所有调用是否返回 false 以及是否返回。调用 odbc_error 找出错误是什么。我的猜测是 oexec 在传递给 obdc_fetch_array 时是错误的。在查看您的帖子以及您正在遵循的教程中使用 PDO,这与使用 ODBC_* 函数不同
    【解决方案3】:

    我终于明白了。

    <?php
    // Location of database. For some reason I could only get it to work in
    // the same location as the site. It's probably an easy fix though
    $dbName = "dbName.mdb";
    $tName = "table";
    
    // Throws an error if the database cannot be found
    if (!file_exists($dbName)) {
        die("Could not find database file.");
    }
    
    // Connects to the database
    // Assumes there is no username or password
    $conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
    
    // This is the query
    // You have to have each column you select in the format tableName.[ColumnName]
    $sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
            FROM $dbName.$tName";
    
    // Runs the query above in the table
    $rs = odbc_exec($conn, $sql);
    
    // This message is displayed if the query has an error in it 
    if (!$rs) {
        exit("There is an error in the SQL!");
    }
    
    $data = array();
    $i = 0;
    
    // Grabs all the rows, saves it in $data
    while( $row = odbc_fetch_array($rs) ) {
        $data[$i] = $row;
        $i++;
    } 
    
    odbc_close($conn); // Closes the connection
    $json = json_encode($data); // Generates the JSON, saves it in a variable
    ?>
    

    【讨论】:

      【解决方案4】:

      我使用此代码将 ODBC 查询的结果放入 JSON 数组:

      $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;
      

      最后以 JSON 格式编码响应:

      echo json_encode($response);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-01
        • 1970-01-01
        • 2013-12-13
        • 2016-01-02
        相关资源
        最近更新 更多