Nicholas J Panella
Nicholas J Panella

Reputation: 109

Shows Table and Values Using Drop Down

In this application I have a drop down so you can select what table you want to view. Using Ajax I push the variable $tbl as an integer and the code below prints out the table that corresponds with that integer. Something is not working though and I need an extra pair of eyes to help debug.

if($tbl == 9){$table = "person";}

    $conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
    $query = mysqli_query($conn, "SELECT * FROM $table ") or die(mysqli_error($conn)); 

if($query){

    echo '<table border="1"><thead><tr>';

    $colnames = array();

    while ($finfo = mysqli_fetch_field($query)) {
        $name=$finfo->name; 

        array_push($colnames, $name);

        echo "<th>".$name."</th>";

    }
    mysqli_free_result($query);

    echo '</tr></thead><tbody>';



    $count = 0; 
    echo $colnames[$count]; // this test prints the correct column name but it ends up being printed OUTSIDE the table for some reason
    while ($row = mysqli_fetch_array($query, MYSQLI_BOTH)){
        echo '<td>'.$row[$colnames[$count]].'</td>';
        $count++;
    }

    echo "</tbody></table>";

}

The last while loop is suppose to echo out each field value but it isn't executing <tbody> is left blank.

Upvotes: 0

Views: 29

Answers (2)

Fabricator
Fabricator

Reputation: 12772

You called mysqli_free_result($query) too early. So by the time you called mysqli_fetch_array, the sql result was already gone. Move mysqli_free_result after the last loop.

Upvotes: 1

theruss
theruss

Reputation: 1746

I'm not sure whether it's a typo or that the following is where the problem lies, but you're missing opening and closing <tr> tags around the column names after <tbody> and before </tbody>. This may help explain why stuff is being printed apparently "outside" the table.

Upvotes: 0

Related Questions