【问题标题】:Printing single result from db2 query in php在 php 中打印来自 db2 查询的单个结果
【发布时间】:2018-11-02 12:47:37
【问题描述】:

我在 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 返回到变量中?

【问题讨论】:

  • 这就是我的想法,但我的 echo 语句没有显示任何内容。它遍历脚本的其余部分,我在执行时有一个 if/else,它打印出它确实执行了,但我需要在终端中查看 ID,但它没有显示
  • 但我需要实际的 sessionid 以便在另一个查询中进行比较好吧,你在 $maxResult 中有它,所以问题就来了。
  • 我不知道我这样做了,我正在尝试通过打印 $maxResult 进行调试,但它没有打印,这意味着我没有它
  • 愚蠢的建议,我不知道 DB2 试试SELECT MAX(SESSIONID) as maxId FROM session 可能在使用实际列名作为别名时存在问题
  • 嗯,没用,但这是一个很好的建议,因为它有时会很挑剔

标签: php sql db2


【解决方案1】:

您将错误的参数传递给 odbc_fetch_row(),因为 $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;

【讨论】:

  • 好吧,我确实喜欢您所做的重构,它实际上仍然可以毫无错误地执行,但由于某种原因仍然没有回显将其传递给我的下一个查询的 ID。我接受了它,因为这是更清洁和更合适的方法。我只需要继续使用 echo 语句
  • 也许我应该使用 fetch_object 而不是 row?
  • 有时回声会丢失,具体取决于您在做什么。如果您稍后在代码中抛出不同的页面,则回显将丢失。
  • 查看编辑后的答案,尝试将回显写入文件而不是回显
  • 啊,好主意。好的,用 maxResult = 写入 txt 文件,它是空白的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多