PHP has several functions related to postgresql - including a function to fetch all the rows of the resultset at once into an array and then have a loop that extracts one row at a time from that :
search for all functions with pg_ prefix --- they are PHP functions relating to PostgreSQL. You need not fetch rows one by one from pg, instead fetch all the result rows into a php array and then loop to read them one by one from that array.