Why is PDO fetchColumn() not working here

前端 未结 2 844
栀梦
栀梦 2021-01-07 15:11

I\'m trying to count the number of rows returned by a query, and I\'m doing like this:

$what = \'Norman\';
$stmt = $conn->prepare(\'select names as names          


        
相关标签:
2条回答
  • 2021-01-07 15:17

    If you want to get the number of rows returned use rowCount

    // ...
    $rows = $stmt->rowCount();
    
    echo 'Rows found '.$rows;
    // ...
    
    0 讨论(0)
  • 2021-01-07 15:21

    Looks like you are using improper functions here.

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

    or you can make it even neater, by getting 1d array instead of 2d

    $rows = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); 
    
    echo 'Rows found '.count($rows);
    
    foreach ($rows as $name)
    {  
        echo $name . "<br>";
    }
    

    But you have to check for PDO errors first

    0 讨论(0)
提交回复
热议问题