使用odbc驱动程序从php中的ms访问数据库2007中检索数据。使用查询检索所有数据,但只检索一条记录而不检索其他数据。
在下面查询三个记录,但仅检索到一个数据。 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
}
?>
答案 0 :(得分:0)
您只返回JSON数据中的一条记录,因为您没有遍历记录集。最初,我误读了您在同一记录集上两次调用odbc_fetch_array
的情况,但仔细检查后发现,据我所知,暗示使用了一个查询,以查看是否有可能从主记录返回的记录查询。以下重新编写的代码尚未经过测试-我没有办法进行测试-仅具有单个查询,但确实尝试遍历循环。
如果出于某种原因需要记录的数量,我将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;
?>