Why is PDO fetchColumn() not working here

前端 未结 2 843
栀梦
栀梦 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: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'] . "
    "; }

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

    But you have to check for PDO errors first

提交回复
热议问题