php - 如何使用 PHP 和 MySQL 填充此 HTML 表

标签 php html mysql

Mysql 文件:

    <?php
  function query($sql, $array) {

    $servername = "localhost";
    $username = "verifyUser";
    $password = "test";
    $dbname = "verify";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $result = $conn->query($sql);

    $stack = array();

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            array_push($stack, $row);
            if(!$array) {
                return $row;
            }
        }
        return $stack;
    }
    $conn->close();

}
?>

我的 php 文件:

    <table>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Serial</th>
    </tr>

    <?php

        include_once("mysql.php");
        $result = query("SELECT ProductId, Name, SerialId FROM product", true);
        while ($row = mysqli_query($result)) {
            echo "<tr><td>" . $row['ProductId'] . "</td><td>" . $row['Name'] . "</td><td>" . $row['SerialId'] . "</td></tr>";
        }

    ?>
</table>

输出:

Id  Name    Serial

这是我尝试用 php 做任何事的第一天。所以对我宽容一些:) 我一直在遵循不同的教程并查看 php 文档,但我无法让我的表打印除表头之外的任何内容。 我不认为我的查询是错误的,因为我在工作台中返回结果 https://gyazo.com/ab588fa7b7498444a5e8dcd1b172f315

最佳答案

<?php
 $table='<table>
            <tr>
             <th>Id</th>
             <th>Name</th>
             <th>Serial</th>
           </tr>';


  $servername = "localhost";
  $username = "";
  $password = "";
  $dbname = "verify";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);

 // Check connection
 if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
  }

 $result = $conn->query($sql);

  $stack = array();

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    array_push($stack, $row);
    if(!$array) {
        return $row;
     }
 }
}

$conn->close();

 $table_content='';
 foreach($stack as $item)
 {
  $table_content.= "<tr>
                     <td>" . $row['ProductId'] . "</td>
                     <td>" . $row['Name'] . " </td>.  
                     <td>" . $row['SerialId'] . "</td>
                   </tr>";

 }
echo $table.$table_content.'</table>';
 ?>

关于php - 如何使用 PHP 和 MySQL 填充此 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54993777/

相关文章:

php - OpenCV & PHP & XAMPP

php - php中的日期时间函数

mysql - "Error Code: 1205. Lock wait timeout exceeded; try restarting transaction"删除事件

php - $POST PHP 问题

php - 按日期顺序查询连续结果

php - 将 strtotime() 转换为 StrFTime()

php - 使用 PHP 从 SQL 数据库传递选择值

调整浏览器大小时的 CSS Div 页脚

html - 如何将 div 自动对齐到新列

javascript - 使用 JS 在 <canvas> 中显示当前日期和时间