0

我正在尝试计算查询返回的行数,我正在这样做:

$what = 'Norman';
$stmt = $conn->prepare('select names as names from names where names = :what');
$stmt->bindParam('what', $what);
$stmt->execute();
$rows = $stmt->fetchColumn();

echo 'Rows found '.$rows;

$stmt->setFetchMode(PDO::FETCH_ASSOC);

while($row = $stmt->fetch())
{  
    echo $row['names'] . "<br>";
}

但我一直一无所获。只是空白。这样做的正确方法是什么?

4

2 回答 2

6

看起来您在这里使用了不正确的功能。

$what = 'Norman';
$stmt = $conn->prepare('select names from names where names = ?');
$stmt->execute(array($what));
$rows = $stmt->fetchAll(); // it will actually return all the rows

echo 'Rows found '.count($rows);

foreach ($rows as $row)
{  
    echo $row['names'] . "<br>";
}

或者您可以通过获取 1d 数组而不是 2d 来使其更整洁

$rows = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); 

echo 'Rows found '.count($rows);

foreach ($rows as $name)
{  
    echo $name . "<br>";
}

但是你必须先检查 PDO 错误

于 2013-04-26T09:48:13.483 回答
1

如果要获取返回的行数,请使用rowCount

// ...
$rows = $stmt->rowCount();

echo 'Rows found '.$rows;
// ...
于 2013-04-26T09:43:04.617 回答