查询中的SQL查询(PHP)

So I've got myself some php below that is intended to find the columns of the spikes table and build an html table accordingly with the results of the spikes query.

Naturally, I don't want to be running a query for each loop, so I defined $schema to query it before the loops. However, if i don't declare it within the while($spike...) section, it just doesn't work. What am I doing wrong here?

And please do not give me a proprietary response. I'm trying to stick to writing code as cross-compatible between sql solutions as possible.

// Queries
$q_spikes = "SELECT * FROM spikes";
$q_schema = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'spikes'";


// Table
echo "<table>";

    echo "<tr>";
    $schema = $conn->query($q_schema);

    while($info = $schema->fetch_assoc()) {
        echo "<td>" . $info['COLUMN_NAME'] . "</td>";
    }
    echo "</tr>";

    $spikes = $conn->query($q_spikes);

    while($spike = $spikes->fetch_assoc()) {

        echo "<tr>";

        $schema = $conn->query($q_schema);

        while($info = $schema->fetch_assoc()) {
            echo "<td>" . $spike[$info['COLUMN_NAME']] . "</td>";
        }
        echo "</tr>";

    }

echo "</table>";

Based on RiggsFolly's comment, I was able to achieve my goal with this:

    // Queries
    $q_spikes = "SELECT * FROM spikes";
    $needshead = true;

    // Table
    echo "<table>";
        $spikes = $conn->query($q_spikes);
        while($spike = $spikes->fetch_assoc()) {
            if($needshead) { 
                $needshead = false;
                echo '<tr>';
                    foreach ($spike as $key => $value) {
                    echo '<td>' . $key . '</td>';   
                    }
                echo '<tr>';
            }
            echo "<tr>";
                foreach ($spike as $key => $value) {
                    echo "<td>" . $value . '</td>'; 
                }
            echo "</tr>";
        }
    echo "</table>";