dssk35460 2017-07-26 17:16
浏览 51

查询中的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>";
  • 写回答

1条回答 默认 最新

  • douliexing2195 2017-07-26 18:26
    关注

    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>";
    
    评论

报告相同问题?

悬赏问题

  • ¥15 BV260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序