【问题标题】:Why is PDO fetchColumn() not working here为什么 PDO fetchColumn() 在这里不起作用
【发布时间】:2013-04-26 09:39:54
【问题描述】:

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

$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>";
}

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

【问题讨论】:

标签: php pdo


【解决方案1】:

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

$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 错误

【讨论】:

    【解决方案2】:

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

    // ...
    $rows = $stmt->rowCount();
    
    echo 'Rows found '.$rows;
    // ...
    

    【讨论】:

    • 我认为这不适用于mysql,但它实际上是返回表中的行数。我已经阅读了所有 rowCount() 不适用于选择 {Amazed}。
    • @Norman 它不适用于某些数据库系统。它没有列出工作的那些。
    猜你喜欢
    • 2013-05-16
    • 2019-02-10
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多