我正在从数据库中提取数据,但仅将第一行放入动态生成的html表中。
我尝试添加另一个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>";
此代码提取所有正确的信息并将其放在html表中的正确位置,但是由于某些原因,它不收集以下行数据...
答案 0 :(得分:1)
此行仅提取一行:
$row = $result->fetch(PDO::FETCH_ASSOC);
您需要获取尽可能多的行。一旦没有更多行要提取,该函数将返回FALSE
,因此可以与while
循环一起使用,如下所示:
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
echo "</table>";
答案 1 :(得分:0)
由于您没有为查询准备的任何变量,因此只需执行以下操作即可:
<?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>';
第二种方法是:
<?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>';
答案 2 :(得分:0)
尝试一下
$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>";