Home > Back-end >  Iterate over a fetch call with PDO
Iterate over a fetch call with PDO

Time:11-23

I need to convert a while of a fetch of data in PDO into a for loop. The for loop don't have to be a foreach but something like that:

for($count = 0; .........; $count  ){}

How can i do that? My code now is:

while ($row = $stmt -> fetch(PDO::FETCH_ASSOC)){
    print("<tr>");
    print("<td>".$row['name']."</td>");
    print("<td>".$row['surname']."</td>");
    print("<td>".$row['dateOfBirth']."</td>");
    print("</tr>");
}

CodePudding user response:

The 2nd parameter in a for loop is the condition under which the loop should be executed, which is

$index < $stmt->rowCount()

Official Reference:

https://www.php.net/manual/en/pdostatement.rowcount.php

So the code is

for ($index=0; $index < $stmt->rowCount(); $index  ){

$row = $stmt -> fetch(PDO::FETCH_ASSOC)

 print("<tr>");
    print("<td>".$row['name']."</td>");
    print("<td>".$row['surname']."</td>");
    print("<td>".$row['dateOfBirth']."</td>");
    print("</tr>");

}
  • Related