查询中的SQL查询(PHP)

时间:2017-07-26 17:16:47

标签: php mysql sql tsql

所以我在下面有一些php用于查找spikes表的列并相应地使用spikes查询的结果构建一个html表。

当然,我不想为每个循环运行查询,所以我定义$ schema在循环之前查询它。但是,如果我不在while($ spike ...)部分内声明它,它就不起作用。我在这做错了什么?

请不要给我一个专有的回复。我试图尽可能地将代码编写为sql解决方案之间的交叉兼容。

// 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>";

1 个答案:

答案 0 :(得分:0)

根据RiggsFolly的评论,我能够实现我的目标:

    // 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>";