在不知道列的情况下用PHP打印MySQL表


Print MySQL table in PHP without knowing the columns

我目前正在制作一个专用的"列表管理"系统,在该系统中我将SQL查询存储在数据库中。这样我就可以通过前端创建新的"列表"(基本上是sql查询),并查看它们。

我做了前端,这样你就可以把查询保存到数据库中,在我想要PHP执行的时候,我可以打印出我的一个查询的结果。当我在前端选择一个存储的"列表"时,就会发生这种情况。因此,当我按下其中一个列表时,它应该执行SQL查询。到目前为止,一切都很好。

但是,在不知道存在多少列/什么列的情况下,我如何通过PHP打印一个表(就像您在查看表内容时从phpMyAdmin中获得的表一样)?我希望脚本是动态的,这样我就可以查看各种SELECT查询的结果(在不同的表上)。

有什么建议吗?

与其使用不推荐使用的库,不如使用PDO。

$db = new PDO($dsn); //$dsn is the database connection strings. Depends on your DB.
                     //it can be as simple as "odbc:CONN_NAME"
$stmt = $db->prepare("SELECT * FROM $tablename"); 
//be sure to sanitize $tablename! use a whitelist filter, not escapes!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //fetch as associative array
if($rows){
    //check if there are actual rows!
    $first_row = reset($rows); //Resets the internal pointer, return the first elem.
    $header_str = '<th>' . implode('</th><th>', array_keys($first_row)) . '</th>';
    $table_body_rows = array();
    foreach($rows as $row){
        $table_body_rows[] = '<td>' . 
                                implode('</td><td>', $row) . 
                             '</td>';
    }
    $body_str = '<tr>' . implode('</tr><tr>', $table_body_rows) . '</tr>';
    $tbl = "<table><thead><tr>$header_str</tr></thead><tbody>$body_str</tbody></table>";
} else {
    //something went wrong
}

show tables可能是您需要的

echo "<table><tr>";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
    echo "<td> $row[0] </td>";
}
echo "</tr></table>"
mysql_free_result($result);

如果您需要打印带有标题(列名)的行,您必须这样做:

$result=mysql_query("SELECT * FROM yourtable WHERE 1");
if (mysql_num_rows($result)<1) echo "Table is empty";
else
{
   $row=mysql_fetch_assoc($result);
   echo "<table>";
   echo "<tr>";
   echo "<th>".join("</th><th>",array_keys($row))."</th>";
   echo "</tr>";
   while ($row)
   {
       echo "<tr>";
       echo "<td>".join("</td><td>",$row)."</td>";
       echo "</tr>";
       $row=mysql_fetch_assoc($result);
   }
   echo "</table>";
}

这只是一个基本概念。如果表中的值可能包含HTML标记和其他内容,则需要对$row的所有值应用htmlspecialchar()。这可以通过array_walk()来完成。此外,您没有提到您使用的PHP版本,以及您更喜欢什么MySQL API。有些人建议使用mysqli或PDO,这取决于你根据你喜欢的API重写代码。