Remind first row after getting all data - PHP PDO

I am using php PDO for server connection. just like that

$stmt = $pdo->prepare('call naviSql( ?, ?, ? )');
$stmt->execute( array( $someone, $on_navi, $on_date ) );

while( $row = $stmt->fetch(  )  ) { 

    echo '<a href="http://'.$_SERVER['HTTP_HOST'].'/anbu/home.php?topic='.$row['topic_name'].'" class="list-group-item list-group-item-action justify-content-between"></a>';
}

now after echoing out all the data, how i can remind first row values once again?

1 answer

  • answered 2018-03-11 13:42 Terry

    Use fetchAll instead and store all your results in a variable. The first row can then be accessed by its index, i.e.:

    // Store all fetched rows in a variable
    $results = $stmt->fetchAll();
    
    // Iterate through all your results
    foreach($results as $row) {
        echo '<a href="http://'.$_SERVER['HTTP_HOST'].'/anbu/home.php?topic='.$row['topic_name'].'" class="list-group-item list-group-item-action justify-content-between"></a>';
    }
    
    // Re-access the first row
    $firstRow = $results[0];
    print_r($firstRow);