将MySQL数据库信息放入带有for循环的HTML表中

时间:2015-12-10 16:38:17

标签: php html mysql mysqli

我需要将数据库中的10张专辑放入学校的HTML表格中,我认为它可以使用这样的几个for循环:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Album cover from Database</title>
    <meta name="description" content="" />
    <link rel="stylesheet" href="" type="text/css" />
</head>

<body>

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "album_list";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("error:  " . mysqli_connect_error());
}

$sql = "SELECT * FROM albums";

$albumOne = $albumTwo = $albumThree = $albumFour = $albumFive = $albumSix = $albumSeven = $albumEight = $albumNine = $albumTen = [];
$albumList = [$albumOne, $albumTwo, $albumThree, $albumFour, $albumFive, $albumSix, $albumSeven, $albumEight, $albumNine, $albumTen];
$data_values = ["albumcover", "id", "artist", "albumname", "releasedate", "tracknumber", "genre", "detail", "edit"];
$data_names = ["", "#", "Artiest", "Album", "Jaar", "Nummers", "Genre", "Detail", "Edit"];
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        for ($i = 0; $i < 10; $i++) {
            for ($ii = 0; $ii < 9; $ii++) {
                $albumList[$i][] = $row[$data_values[$ii]];
            }
        }
    }
}

?>

<table>
    <tr>
        <?php
        foreach ($data_names as $name) {
            echo "<td>$name</td>";
        }
        ?>
    </tr>
    <?php
    for ($i = 0; $i < 10; $i++) {
        $oddOrNot = "";
        if ($i % 2 == 0) {
            $oddOrNot = "even";
        } else {
            $oddOrNot = "oneven";
        }
        echo "<tr class=\"$oddOrNot\">";
        for ($ii = 0; $ii < 9; $ii++) {
            if ($ii == 0) {
                echo "<td><img src=\"../week3/img/" . $albumList[$i][$ii] . ".jpg\" /></td>";
            } else if ($ii == 7) {
                echo "<td><a href=\"../week3/11albumdetaildb/" . $albumList[$i][$ii] . ".php\">Detail</a></td>";
            } else if ($ii == 8) {
                echo "<td><a href=\"../week2/7musicalbums3/" . $albumList[$i][$ii] . ".php\">Edit</a></td>";
            } else {
                echo "<td>" . $albumList[$i][$ii] . "</td>";
            }
        }
        echo "</tr>";
    }
    ?>
</table>

</body>

</html>

但这只会导致相同的专辑输出十次。 即使我手动输入所有data_values而不是第二个for循环,它仍然只会输出相同的专辑十次。 因为我只是一个初学者,我真的不知道自己做错了什么。

0 个答案:

没有答案