为什么 {if row exist then fetch them} 不起作用?

why {if row exist then fetch them} does not work?

我想先检查 {if row exist} 然后 fetch 结果。这是我的代码:

$id = 102;

// connecting to database here
$sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
       $sth->execute(array($id));
       $num_rows = $sth->fetchColumn();

  // if exist
  if($num_rows){

       // then fetch
       while($end = $sth->fetch())
       {
           echo $end['id'];
       }

  }

但是输出是空白的,为什么?

需要注意的是数据库中存在id = 102

PDO 也有类似的方法 rowCount 但在某些情况下会 return 影响行。

引用自 PHP 手册

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

根据提示,您可以查询、统计并继续

$id = 102;

// connecting to database here
$sth = $dbh->prepare('SELECT COUNT(*) FROM users WHERE id = ?');
       $sth->execute(array($id));
       $num_rows = $sth->fetchColumn();

// if exist
if($num_rows > 0){

    $sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
  $sth->execute(array($id));

    // then fetch
    while($end = $sth->fetch())
    {
         echo $end['id'];
    }
}

据我了解,此 ID 只有一行。你可以使用 fetch():

$id = 102;

// connecting to database here
$sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
$sth->execute(array($id));
$row = $sth->fetch();

// if record exist
if ($row) {
     var_dump($row);
     die();
}