Sam Bo Hamdan
Sam Bo Hamdan

Reputation: 85

How to create a normal HTML Table filled in with Database Data using php?

Hi im new to frontend world and i made a small sql database filled with some data , i could get the data from database to my php code as Associative Array but the problem is that i cant fill them inside my table , they appear upper and outside the table. with any help i'll be thankful.

<?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>";


}
?>

enter image description of the result here

Upvotes: 1

Views: 121

Answers (3)

clem
clem

Reputation: 3366

You are using print_r inside a string concatenation.

foreach ($value as $key1 => $value1) {
    echo "<tr>
    <td>".print_r($value1['ID'])."</td>
    <td>".print_r($value1['userName'])."</td>
    </tr>";
}

Remove the print_r statements and the values will show up inside the table.

Upvotes: 1

Krysan
Krysan

Reputation: 11

A quick&dirty solution,not tested :-

<?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>";
}
?>

Upvotes: 0

Liogate
Liogate

Reputation: 165

Your tbody tag should be parent of all your tr elements and your header in thead. Check this struct bellow:

<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>

Upvotes: 0

Related Questions