在网页上的 HTML 表中显示 MySQL 数据库表中的值

2022-08-30 10:22:40

我想从数据库表中检索值,并在页面的html表中显示它们。我已经搜索了这个,但我找不到答案,尽管这肯定很容易(这应该是数据库的基础知识)。我想我搜索过的术语具有误导性。数据库表名称是票证,它现在有6个字段(submission_id,formID,IP,名称,电子邮件和消息),但应该有另一个名为ticket_number字段。我如何让它在html表中显示db中的所有值,如下所示:

<table border="1">
  <tr>
    <th>Submission ID</th>
    <th>Form ID</th>
    <th>IP</th>
    <th>Name</th>
    <th>E-mail</th>
    <th>Message</th>
  </tr>
  <tr>
    <td>123456789</td>
    <td>12345</td>
    <td>123.555.789</td>
    <td>John Johnny</td>
    <td>johnny@example.com</td>
    <td>This is the message John sent you</td>
  </tr>
</table>

然后是“约翰”下面的所有其他值。


答案 1

取自 W3Schools 的示例:PHP 从 MySQL 中选择数据

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

这是一个学习的好地方!


答案 2

试试这个:(完全动态...)

<?php
$host    = "localhost";
$user    = "username_here";
$pass    = "password_here";
$db_name = "database_name_here";

//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($host, $user, $pass, $db_name);

//get results from database
$result = mysqli_query($connection, "SELECT * FROM products");
$all_property = array();  //declare an array for saving property

//showing property
echo '<table class="data-table">
        <tr class="data-heading">';  //initialize table tag
while ($property = mysqli_fetch_field($result)) {
    echo '<td>' . $property->name . '</td>';  //get field name for header
    $all_property[] = $property->name;  //save those to array
}
echo '</tr>'; //end tr tag

//showing all data
while ($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    foreach ($all_property as $item) {
        echo '<td>' . $row[$item] . '</td>'; //get items using property value
    }
    echo '</tr>';
}
echo "</table>";

推荐