You're not setting the ri form field:
$row = $ri + 1;
$ri = $row;
print "<FORM method=\"POST\" action=\"$PHP_SELF\"> <INPUT type=\"hidden\" name=\"ri\" value="$ri"> <P><INPUT type=\"submit\" value=\"Next\"></p> </FORM>\n";
Incidentally, if you're not using $row for anything else you can replace those first two lines with
$ri++;