Norman
Norman

Reputation: 6365

PDO and MySql loop outputs only one row when there are several

$stmt = $conn->prepare($sql);
$stmt->execute($array);
$rows = $stmt->rowCount();

    if($rows >= 1) {
        $x = $stmt->fetch();

        echo '<div>'.$x['heading'].'</div>';

        while($row = $stmt->fetch()) {
            echo '<div>'.$row['article'].'</div>';
        }
    } else {
        echo 'Nothing found';
    }

When doing like above, can you see why the loop outputs only one row when there are several? It happens when I use fetch twice.

Also, how can I avoid having to use fetch twice in there? It's fetched once, can i use that same fetched data again?

Upvotes: 1

Views: 95

Answers (2)

Luke
Luke

Reputation: 23680

You can use fetchAll() to get all of the data in the result set as an array.

You can reuse the data by assigning it to a variable:

// Fetch all returned rows
$my_rows = $stmt->fetchAll();

// Make use of these rows multiple times
foreach ($my_rows AS $single_row)
{
    echo $single_row['column_name'];
}

// Make use of the retult set a second time
foreach ($my_rows AS $single_row)
{
    echo $single_row['column_name'];
}

Upvotes: 0

Millard
Millard

Reputation: 1157

$stmt->fetchAll()

maybe this?

Upvotes: 1

Related Questions