Jarrod
Jarrod

Reputation: 95

php variable results in while loop displaying data in infinite loop

I'm confused about how these snippets of code differ in displaying results in a while loop. The first snippet of code works perfectly but the second displays the results but does so in an infinite loop and just repeats the results. Can someone explain to me why?

$stmt = $db_conn->prepare($sql);

$stmt->execute(array("Lorna", 3));

while($result = $stmt->fetch()){
    echo $result["name"] . "<br />" . $result["description"] . "<br />";        
}

If I put $stmt->fetch() into a variable called $data and try to pass this instead of just putting $stmt->fetch() in the while loop, I get an infinite loop.

$stmt = $db_conn->prepare($sql);

$stmt->execute(array("Lorna", 3));

$data = $stmt->fetch();

while($result = $data){
    echo $result["name"] . "<br />" . $result["description"] . "<br />";        
}

Thanks in advance!

Upvotes: 2

Views: 873

Answers (3)

Adam Hopkinson
Adam Hopkinson

Reputation: 28793

In the first code snippet, each time while is called, the query result pointer moves to a new row. Eventually the pointer will reach the end of the result set, and $stmt->fetch() will return false and end the loop.

In the second loop, you are only iterating to the next row once - before the loop. The loop will then iterate the same loop over and over, as nothing changes so the loop condition never returns false.

Upvotes: 2

Paolo
Paolo

Reputation: 15847

The first loop check the value returned from the function that could be null causing the loop to end.

The second loop just make an assignment.

Upvotes: 1

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46788

If is the call to fetch() which makes the rows advance.

case 1

while($result = $stmt->fetch()){
    //every iteration executes fetch
    //advances it by one row
    //turns to false when no more rows
}

case 2

$data = $stmt->fetch();
//now at first row
while($result = $data){
    //always at first row 
    //always evaluates to true (no calls to fetch)
}

Upvotes: 2

Related Questions