简体   繁体   English

在PDO :: FETCH_OBJ循环中没有返回找到的记录值

[英]Return No Record Found Value in PDO::FETCH_OBJ Loop

I need to add an if/then into my PDO::FETCH_OBJ result statement to display a "No Records Found" message if the query is blank. 如果查询为空,我需要在我的PDO :: FETCH_OBJ结果语句中添加一个if / then,以显示“未找到记录”消息。

My working query: 我的工作查询:

          <?php
          $command  = "SELECT ";
          $command .= "id, ";
          $command .= "firstName, ";
          $command .= "FROM mytable ";
          $command .= "ORDER BY sortOrder";

          $STH = $DBH->query($command);  

          $STH->setFetchMode(PDO::FETCH_OBJ);  

          while($row = $STH->fetch()) { ?>
          <tr>
            <td><a href="view/?b=<?php echo $row->id; ?>"><?php echo $row->firstName; ?></a></td>
          </tr>
          <?php } ?>

I was able to find similar code that would work for an array, but I can't get it to work with the FETCH_OBJ code above. 我能够找到适用于数组的类似代码,但无法与上面的FETCH_OBJ代码一起使用。

This is similar code that illustrates the if/then I would like to implement: 这是类似的代码,说明了我想实现的if / then:

  $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
  $stmt->execute(array('id' => $id));

  $result = $stmt->fetchAll();

  if ( count($result) ) {
    foreach($result as $row) {
      print_r($row);
    }  
  } else {
    echo "No rows returned.";
  }

I'm brand new to PDO so I'm sure it's a context issue, I just can't get it to work. 我是PDO的新手,所以我确定这是一个上下文问题,我无法使其正常工作。

Set a variable to determine if you found any rows during the loop. 设置变量以确定在循环过程中是否找到任何行。

$no_rows_found = true;
while ($row = $STH->fetch() {
    $no_rows_found = false;
    ...
}

if ($no_rows_found) {
    echo "No rows found";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM