Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate over a fetch call with PDO

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>");
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>");

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading