How to find a variable that works?

Try var_dump( $result ); and there should be a row count that can be tested before outputting the headers.