【问题标题】:I think PDO fetch() and fetchColumn() block each other我认为 PDO fetch() 和 fetchColumn() 互相阻塞
【发布时间】:2019-08-09 15:38:00
【问题描述】:

所以我正在试验 PDO 查询。看看这个sn-p:

1. $rows = $stmt->fetchColumn();
2. echo $rows;
3. $row = $stmt->fetch();
4. print_r($row);

这只是一个观察结果......不确定有多真实! 执行第 2 行并返回行数(在我的情况下为 1,因为我只是在验证用户)。 第 4 行不返回任何内容。

如果你颠倒了订单:

1. $row = $stmt->fetch();
2. print_r($row);
3. $rows = $stmt->fetchColumn();
4. echo $rows;

第 2 行的数组已打印,但第 4 行没有返回任何内容!这是正确的行为吗?

无论如何,我如何实现以下结果?

if ($stmt->fetchColumn() == 1) {
    $row = $stmt->fetch();
    print_r($row);
} else {
    echo '<div class="error-message">Verify Your Credentials</div>';
}

【问题讨论】:

    标签: mysql pdo


    【解决方案1】:

    这个答案可能会帮助你PDO fetch one column from table into 1-dimensional array

    fetchColumn 只返回一个结果,但是您可以使用 pdo::fetch 方法以不同的方式展平您的结果,您应该查找它们,它们会快速简单地整理您的结果。尝试阅读更多内容https://phpdelusions.net/pdo/fetch_modes

    【讨论】:

      【解决方案2】:

      这是正确的行为,fetchColumn 获取一列。你不能拿它两次。您可以使用:

      /* fetches row from the result, if theres no row in the result, fetch returns false */
      $row = $stmt->fetch(); 
      
      /* compare if $row is true (in PHP, "boolean value" of unempty array is true) */
      if ( $row ) { 
          print_r($row);
      } else {
          echo '<div class="error-message">Verify Your Credentials</div>';
      } 
      

      【讨论】:

      • 这很容易解决!你能解释一下幕后到底发生了什么吗?
      • @ckwagaba fetching 表示该行是从结果集中获取的。因此,当您第一次调用 fetchColumn 时,它会将行从结果集中“取出”,然后当您随后尝试调用 fetch 时,就没有剩余行了。我还将在原始答案中的代码中添加一些 cmets。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      相关资源
      最近更新 更多