我正在尝试计算查询返回的行数,我这样做:
$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>";
}
但我一点也没有得到任何东西。只是空白。什么是正确的方法呢?
答案 0 :(得分:4)
看起来你在这里使用了不正确的功能。
$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错误
答案 1 :(得分:3)
如果要获取返回的行数,请使用rowCount
// ...
$rows = $stmt->rowCount();
echo 'Rows found '.$rows;
// ...