首页 > 解决方案 > 在 php 中打印来自 db2 查询的单个结果

问题描述

我在 php 脚本中对 db2 运行查询,该脚本运行成功,但我无法让它回显我选择的记录的实际 ID。它确实回显了我的成功声明,显示它运行成功,但我需要sessionid在另一个查询中进行实际比较。

这里我选择记录,执行查询并检查执行,但我也尝试使用 fetch_row 和 result 来返回单个选定的 ID:

$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);

while(odbc_fetch_row($executeSessionMax)){
  $maxResult = odbc_result($executeSessionMax, "SESSIONID");
  echo $maxResult;
}

如何从 db2 正确地将 sessionID 返回到变量中?

标签: phpsqldb2

解决方案


您将错误的参数传递给odbc_fetch_row()as$executeSessionMax是 True 或 False,具体取决于成功执行。

$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);

while(odbc_fetch_row($prepareSessionMax )){
//  correction here  ^^^^^^^^^^^^^^^^^^
  $maxResult = odbc_result($executeSessionMax, "SESSIONID");
  echo $maxResult;
}

您可以重新编码,因为 MAX() 只会返回一行,因此也不需要 while 循环。

$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
if (odbc_execute($prepareSessionMax)) {

    odbc_fetch_row($prepareSessionMax );
    $maxResult = odbc_result($executeSessionMax, "SESSIONID");
    echo $maxResult;
    // if echo gets lost try writing to a file
    error_log("maxResult = $maxResult", 3, "my-errors.log");

} else {
    // something went wrong in the execute
}

你也可以试试

$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$result = odbc_exec($DB2Conn, $latest_result);
$rows = odbc_fetch_object($result); 
echo $row->SESSIONID;
$maxResult = $row->SESSIONID;

推荐阅读