简体   繁体   English

从数据库中提取数据并进入html表

[英]Pulling data from database and into an html table

I'm pulling data from a database but only getting the first row into the dynamically produced html table. 我从数据库中提取数据,但只将第一行放入动态生成的html表中。

I've tried adding another foreach loop but that isn't the answer… I'm out of ideas... 我已经尝试添加另一个foreach循环,但这不是答案......我没有想法......

$conn = new PDO('mysql:host=localhost;dbname=jeuxvideo', $dbUserName, $dbPassword);
$sql = "SELECT * FROM jeuxvideo";
$result = $conn->prepare($sql);
$request = $result->execute();

echo "<table border='1'>";
echo "<tr><td>Id</td><td>Titre</td><td>Prix<td>Date de Sortie</td><td>Genre</td><td>Origine</td><td>Mode</td><td>Connexion</td></tr>\n";
$row = $result->fetch(PDO::FETCH_ASSOC);

echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
echo "</table>";

This code pulls all the correct info and puts it in the right place in the html table, but for some Reason it doesn't collect the Following rows data... 此代码提取所有正确的信息并将其放在html表中的正确位置,但由于某些原因,它不会收集以下行数据...

This line only fetches one row: 此行仅获取一行:

$row = $result->fetch(PDO::FETCH_ASSOC);

You need to fetch as many rows it can give you. 您需要获取它可以为您提供的行数。 Once there are no more rows to fetch the function will return FALSE , so you can use with the while loop, like this: 一旦没有更多的行来获取该函数将返回FALSE ,因此您可以使用while循环,如下所示:

while($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo "<tr>";
    foreach ($row as $key => $value) {
        echo "<td>$value</td>";
    }
    echo "</tr>";
}
echo "</table>";

Since you don't have any variables you need prepared for your query, you can simply do: 由于您没有为查询准备的任何变量,因此您可以执行以下操作:

<?php
$stmt = $pdo->query('SELECT * FROM jeuxvideo');

echo '<table>';

foreach ($stmt as $row) {
    echo '<tr>';

    echo "<td>$row['name']</td>";
    echo "<td>$row['url']</td>";
    echo "<td>$row['timestamp']</td>";

    echo '</tr>';
}

echo '</table>';

A 2nd method would be: 第二种方法是:

<?php
$stmt = $pdo->query('SELECT * FROM jeuxvideo');

echo '<table>';

while ($row = $stmt->fetch()) {
    echo '<tr>';

    echo "<td>$row['name']</td>";
    echo "<td>$row['url']</td>";
    echo "<td>$row['timestamp']</td>";

    echo '</tr>';
}

echo '</table>';

Try this 尝试这个

 $conn = new PDO('mysql:host=localhost;dbname=jeuxvideo', $dbUserName, $dbPassword);
$sql = "SELECT * FROM jeuxvideo";
$result = $conn->prepare($sql);
$request = $result->execute();

echo "<table border='1'>";
echo "<tr><td>Id</td><td>Titre</td><td>Prix<td>Date de Sortie</td><td>Genre</td><td>Origine</td><td>Mode</td><td>Connexion</td></tr>\n";

$row = $request->fetch_all();

echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
echo "</table>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM