我正在尝试计算查询返回的行数,我这样做:
$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>";
}
Run Code Online (Sandbox Code Playgroud)
但我始终一无所获。只是空白。这样做的正确方法是什么?
看起来您在这里使用了不正确的功能。
$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>";
}
Run Code Online (Sandbox Code Playgroud)
或者你可以让它更整洁,通过获取一维数组而不是二维数组
$rows = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
echo 'Rows found '.count($rows);
foreach ($rows as $name)
{
echo $name . "<br>";
}
Run Code Online (Sandbox Code Playgroud)
但是你必须先检查 PDO 错误
| 归档时间: |
|
| 查看次数: |
11624 次 |
| 最近记录: |