警告:pg_fetch_array():3不是有效的PostgreSQL结果资源

I'm trying to print out some records in a database to a table:

    session_start();
if(!isset($_SESSION['studentnum'])){
    echo "Please "."<a href='login.php'>login</a>";
    exit;
}

$host = "localhost";
$username = "xyz";
$password = "abc";
$database = "mno";
$port = "5432";

$dbh = pg_connect("host=".$host." port=".$port." dbname=".$database." user=".$username." password=".$password);
if (!$dbh){
    die("Error in connection: ".pg_last_error());
}
$studentnum = $_SESSION['studentnum'];


$sql = "select * from project.student s, project.courses c 
where s.student_num = c.student_num and s.student_num='".$studentnum."'";
$result = pg_query($sql) or die('Query failed: ' . pg_last_error());
pg_free_result($result);
pg_close($dbh);

and then

<?php
while ($line = pg_fetch_array($result)) {  <= this is line 52
    echo "\t<tr>
";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>
";
    }
    echo "\t</tr>
";
}
?>

but I'm getting this error:

 SCREAM: Error suppression ignored for
( ! ) Warning: pg_fetch_array(): 3 is not a valid PostgreSQL result resource in D:\wamp\wwwecords.php on line 52

What did I do wrong? I used this same code somewhere else and it worked, so I'm not sure what's missing here.

I figured it out. I accidentally called pg_free_result($result); before using $result