如果查询为空,我需要在我的PDO :: FETCH_OBJ结果语句中添加if / then以显示“No Records Found”消息。
我的工作查询:
<?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 } ?>
我能够找到适用于数组的类似代码,但我无法使用上面的FETCH_OBJ代码。
这是类似的代码,说明了我想要实现的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.";
}
我是PDO的新手,所以我确定这是一个背景问题,我无法让它发挥作用。
答案 0 :(得分:0)
设置变量以确定在循环期间是否找到任何行。
$no_rows_found = true;
while ($row = $STH->fetch() {
$no_rows_found = false;
...
}
if ($no_rows_found) {
echo "No rows found";
}