全部从 php 中的 MS 访问数据库中检索数据

all retrieve data from ms accesss database in php

使用 odbc 驱动程序从 php 中的 ms access 数据库 2007 检索数据。使用查询检索所有数据但它只获取一条记录检索其他数据未检索。

下面查询了3条记录,但只检索到一条数据。 php 中代码下方的哪个问题?如何使用此代码中的查询获取所有数据 它发生了什么变化?

 <?PHP

    include 'Connection2.php';



    $sql = "select FYearID,Description,FromDate,ToDate  from mstFinancialyear";


    $stmt = odbc_exec($conn, $sql);
    //print_r($stmt);
    $rs = odbc_exec($conn, "SELECT Count(*) AS counter from mstFinancialyear");

    //print_r($stmt);

    $arr = odbc_fetch_array($rs);
    $arr1 = $arr['counter'];
    $result = array(); 

    //print_r($arr);


     if (!empty($stmt)) {

            // check for empty result
            if ($arr1 > 0) {
    // print_r($stmt);

                $stmt1 = odbc_fetch_array($stmt);




               $year = array();
                $year['FYearID'] = $stmt1['FYearID'];
                $year['Description'] = $stmt1['Description'];
                $year['FromDate'] = $stmt1['FromDate'];
                $year['ToDate'] = $stmt1['ToDate'];


                // success
                $result["success"] = 1;

                // user node
                $result["year"] = array();


                array_push($result["year"], $year); 

                echo json_encode($result);

                //return true;

            } else {
                // no product found
                $result["success"] = 0;
                $result["message"] = "No product found";




                echo json_encode($result);


            }


            odbc_close($conn); //Close the connnection first
    }

    ?>

您 return 在 JSON 数据中只有一条记录,因为您没有遍历记录集。最初我误读了你在同一个记录集上调用了 odbc_fetch_array 两次,但仔细检查后发现暗示使用了一个查询,据我所知,看看是否有任何记录可能是 return 从主查询编辑。下面重写的代码尚未经过测试——我没有办法这样做——并且只有一个查询但确实尝试遍历循环。

我将 count 作为子查询包含在主查询中,如果出于某种原因需要记录的数量 - 但是我不认为它是。

<?php

    include 'Connection2.php';

    $result=array();

    $sql = "select 
            ( select count(*) from `mstFinancialyear` ) as `counter`,
            `FYearID`, 
            `Description`,
            `FromDate`,
            `ToDate` 
        from 
        `mstFinancialyear`";

    $stmt = odbc_exec( $conn, $sql );

    $rows = odbc_num_rows( $conn );
    /* odbc_num_rows() after a SELECT will return -1 with many drivers!! */


    /* assume success as `odbc_num_rows` cannot be relied upon */
    if( !empty( $stmt ) ) {

        $result["success"] = $rows > 0 ? 1 : 0;
        $result["year"] = array();

        /* loop through the recordset, add new record to `$result` for each row/year */
        while( $row=odbc_fetch_array( $stmt ) ){ 

            $year = array();
            $year['FYearID'] = $row['FYearID'];
            $year['Description'] = $row['Description'];
            $year['FromDate'] = $row['FromDate'];
            $year['ToDate'] = $row['ToDate'];

            $result["year"][] = $year;

        }
        odbc_close( $conn );
    }

    $json=json_encode( $result );
    echo $json;
?>