环境:
windows、php7.4.3、odbc函数链接MS数据库
原因:
SQL查询返回了N个结果,需要获取到最后一次的结果。
解决:
// sql中有多条语句有返回值,跳过第一个返回值
// TODO 此处需要抑制 warning 信息
while(!odbc_cursor($source_db_res)){
$next_flag = odbc_next_result($source_db_res);
}
附带全程PHP代码:
// 来源数据库
$source_db_config = array(
'dbhost' => '127.0.0.1',
'dbuser' => 'sa',
'dbpwd' => 'Password',
'dbname' => 'iNethinkCMS',
'dblanguage' => 'utf-8',
);
$source_db_link = odbc_connect('DRIVER={SQL Server};SERVER=' . $source_db_config['dbhost'] . ';DATABASE=' . $source_db_config['dbname'] . '', $source_db_config['dbuser'], $source_db_config['dbpwd']);
if (odbc_error($source_db_link))
{
echo '<h2 style="color: red;">SOURCE-来源数据库连接失败: ' . odbc_errormsg($source_db_link) . '</h2>';
echo '<script>setTimeout(function(){alert("SOURCE-来源数据库连接失败:' .odbc_errormsg($source_db_link) . '");}, 100);</script>';
exit();
}
// 获取来源数据 如果有附加表数据则直接 LEFT JOIN additional_table 处理
//-- 假设 @PageSize 是每页显示的记录数,@PageNumber 是当前页码
$source_data = array();
$source_select_sql = <<<SQL
DECLARE @PageSize INT = 100;
DECLARE @PageNumber INT = 1;
SELECT
*
FROM
iNethinkCMS_Content
WHERE
Cid = 4
ORDER BY ID ASC
OFFSET (@PageNumber - 1) * @PageSize ROWS
FETCH NEXT @PageSize ROWS ONLY
SQL;
// 不分页查询表所有数据
//$source_select_sql = <<<SQL
//
//SELECT
// *
//FROM
// iNethinkCMS_Content
//WHERE
// Cid = 16
//ORDER BY ID ASC
//
//SQL;
$source_db_res = odbc_exec($source_db_link, $source_select_sql);
odbc_longreadlen($source_db_res, "100000"); //解决字段字符长度4096 方法二 最大为1亿+
// sql中有多条语句有返回值,跳过第一个返回值
// TODO 此处需要抑制 warning 信息
while(!odbc_cursor($source_db_res)){
$next_flag = odbc_next_result($source_db_res);
}
if (odbc_error($source_db_link))
{
echo '<pre>';
var_dump(odbc_errormsg($source_db_link));
echo '</pre>';
}
if ($source_db_res) {
while($row = odbc_fetch_array($source_db_res)){
$temp = array();
foreach($row as $key=>$val){
$temp[$key] = addslashes(mb_convert_encoding($val, "utf-8", 'gb2312'));
}
$source_data[] = $temp;
}
odbc_free_result($source_db_res);
} else {
echo '<pre>';
var_dump(odbc_errormsg($source_db_link));
echo '</pre>';
exit();
}
// TODO 此处打印来源数据请自行检查是否正确
var_dump($source_data); exit();
// TODO 其他数据操作
// 判断并释放资源
if($source_db_link){
odbc_close($source_db_link);
}
参考:
sql - ODBC error in PHP: "No tuples available at this result index" - Stack Overflow