嗨我是前端世界的新手,我做了一个小的SQL数据库,里面装满了一些数据,我可以将数据从数据库中获取为我的PHP代码作为关联数组,但问题是我不能将它们填入我的表中,它们出现了桌子上方和外面。在任何帮助下,我都会感恩。
<?php
include("page.html");
include("databaseConnection.php");
$sth = $conn->prepare("SELECT ID, userName from passwords");
$sth->execute();
$result[] = $sth->fetchAll();
if(isset($_POST["showData"])){
echo "<table style='border: 2px solid black'>
<tr>
<th style='border: 1px solid red'>ID</th>
<th style='border: 1px solid black'>User Name</th>
</tr> <tbody>";
foreach ($result as $key => $value) {
foreach ($value as $key1 => $value1) {
echo "<tr>
<td>".print_r($value1['ID'])."</td>
<td>".print_r($value1['userName'])."</td>
</tr>";
}
}
echo "</tbody></table>";
}
?>
答案 0 :(得分:1)
您在字符串连接中使用print_r。
foreach ($value as $key1 => $value1) {
echo "<tr>
<td>".print_r($value1['ID'])."</td>
<td>".print_r($value1['userName'])."</td>
</tr>";
}
删除print_r语句,值将显示在表格内。
答案 1 :(得分:0)
快速而肮脏的解决方案,未经测试: -
<?php
include("page.html");
include("databaseConnection.php");
$sth = $conn->prepare("SELECT ID, userName from passwords");
$sth->execute();
$result[] = $sth->fetchAll();
if(isset($_POST["showData"])){
echo "<table style='border: 2px solid black'>
<tr>
<th style='border: 1px solid red'>ID</th>
<th style='border: 1px solid black'>User Name</th>
</tr> <tbody>";
foreach ($result as $key => $value) {
foreach ($value as $key1 => $value1) {
?>
<tr>
<td><? echo $value1['ID']; ?></td>
<td><? echo $value1['userName']; ?></td>
</tr>
<?php
}
}
echo "</tbody></table>";
}
?>
答案 2 :(得分:0)
你的tbody标签应该是你所有tr元素的父级和你在thead中的标题。检查以下结构:
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>