首页 > 解决方案 > 使用 PHP 文件从 PHP MyAdmin 中选择表

问题描述

美好的一天,我正在尝试从 MySQL 中选择一个表,通常我使用以下代码:

$sql="CALL selectCreatedTableByName('".$tableNameIn."')";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table id='restable'>";
    while($row = $result->fetch_assoc()) {
        echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['nameE'] . "</td>";
echo "<td>" . $row['nameN'] . "</td>";
    echo "</tr>";
    }
    echo "</table>";
}

$conn->close();

但是现在,当我不知道表格列的名称时,我该如何选择这个表格?

非常感谢。

标签: phpmysql

解决方案


您不是在选择表格,而是从表格中选择。(至少我猜是这种情况,因为我们不知道您的程序实际上是做什么的)。

返回的 PHP 数组使用结果集中的属性名称作为键,因此......

while($row = $result->fetch_assoc()) {
    echo "<tr>\n";
    foreach($row as $name=>$value) {
        echo "<td>$value</td>\n";
    }
    echo "</tr>\n";
}

如果您想要标题行,请使用状态变量标记第一行。

$fetched=0;
while($row = $result->fetch_assoc()) {
    if (!fetched) {
        echo "<tr>\n";
        foreach($row as $name=>$value) {
            echo "<th>$name</th>\n";
        }
        echo "</tr>\n";
    }
    $fetched++;
    echo "<tr>\n";
    foreach($row as $name=>$value) {
        echo "<td>$value</td>\n";
    }
    echo "</tr>\n";
}

推荐阅读