1
$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?

2
  • php.net/manual/en/pdostatement.fetch.php fetch is for a single row. You should try fetchAll(). Commented Oct 14, 2013 at 16:22
  • 1
    But the OP has a loop to fetch one row at a time. Maybe only one row has been returned? Commented Oct 14, 2013 at 16:24

2 Answers 2

1
$stmt->fetchAll()

maybe this?

Sign up to request clarification or add additional context in comments.

4 Comments

I'm not sure how this answers the question. Using fetch() in a while loop is perfectly fine.
fetch works fine when used alone. Add another, and there's a problem.
@Norman What is the problem with fetching more than once? This page has many examples using a while loop to fetch: php.net/manual/en/pdostatement.fetch.php
@CommuSoft Yes, but the while loop will continue to run as long as there are results in $stmt. It fetches one row upon each iteration until there are no more rows to fetch. I'm not sure how fetchAll() solves the issue here.
0

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'];
}

2 Comments

When using fetchAll, is it possible to directly access a value without the loop. Eg: $my_rows['heading']
@Norman All of your rows are fetched into the array. So you'd do $my_rows[0]['heading'] for the first row. Try echo"<pre>".print_r($my_rows,true)."</pre>" to see the array structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.