从MySQL表中选择所有列

时间:2016-03-16 05:51:51

标签: php mysql

我很难回应某些表中某些列的内容取决于用户选择 - 现在我只有一个表和下面的代码工作完美但当然其他表没有相同的列名和值,所以我尝试修改它 - 到目前为止我被困住了。我怎么能让它变得动态?

谦虚地请求帮助:)

<?php
function showTables($table, $order) {
    global $conn;
    $query = ("SELECT * FROM $table ORDER BY $order ASC LIMIT 0, 30 ");
    $returnTables = mysqli_query($conn, $query);

    while ($row = mysqli_fetch_assoc($returnTables)) {
        $id = $row['id'];
        $name = $row['name'];
        $surrname = $row['surrname'];
        $email = $row['email'];
        $firstTime = $row['firstTime'];
        $comment = $row['comment'];

        echo "<tr>";    
            echo "<td>$name</td>";
            echo "<td>$surrname</td>";
            echo "<td>$email</td>";
            echo "<td>$firstTime</td>";
            echo "<td>$comment</td>";         
            echo "<td class='no-print'><a href='admin.php?delete={$id}'>Usuń</a></td>"; 
        echo "</tr>";
    }
}
?>

1 个答案:

答案 0 :(得分:1)

从TABLE中简单获取列名称,

例如

$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);

while($row = mysqli_fetch_array($result)){
  echo $row['Field']."<br>";
}

编辑2:

完成动态示例(需要格式化tr和td)

function showTables($table, $order) {

    global $conn;

    $query = "SELECT * FROM $table ORDER BY $order ASC LIMIT 0, 30 ";
    $returnTables = mysqli_query($conn, $query);

    $sql_columns_name = "SHOW COLUMNS FROM $table";

    $sql_columns_result = mysqli_query($conn,$sql_columns_name);

    $column_arr = array();

    while($row = mysqli_fetch_array($sql_columns_result)){
      $column_arr[] = $row['Field'];
    }

    echo '<table>';

    while ($row = mysqli_fetch_array($returnTables)) {

        for ($i=0; $i < count($column_arr); $i++) {
            echo "<tr>";  
              echo "<td>".$row[$column_arr[$i]]."</td><br>";
            echo "</tr>";
        }

    }

    echo '</table>';
}