artur47wien artur47wien - 6 months ago 12
HTML Question

Display data from database in a table

I've got something like this, the function allows me to display data from the database "demo", from "products" table:

class Product
{
private $conn;
private $id;
private $name;
private $description;
private $price;
private $category_id;
private $category_name;
private $created;

public function __construct($db)
{
$this->conn = $db;
}

public function readAll()
{
$stmt = $this->conn->prepare('SELECT name, description, price, CategoryID, created FROM products');
$stmt->execute();
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$n = $result['name'];
$d = $result['description'];
$p = $result['price'];
$ca = $result['CategoryID'];
$c = $result['created'];
echo $n . " - " . $d . " - " . $p . " - " . $ca . " - " . $c . "<br />" . "<br />";
}
}
}


Here is my database connection:

class Database {

public function getConnection() {
$result = false;
try {
$result = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
} catch(PDOException $e) { }
return $result;
}
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
die("Error connecting to the database");
}


I can display data like this:

<div>
<h3>readAll:</h3>
<form action="" method="post">
<label>Products: <br /> (Name - Description - Price - Category ID - Creation date): </label><br />
<?php
$cat = new Product($conn);
echo $cat->readAll();
?>
</form>
</div>


But how can I display data from the database in a table?

Answer

Here's a clue, and it all depends on how your php is structured.

Just before the while loop,

  echo '<table>';

// you can add table head if you please

 While(...){

    $a = $row['...'];

    echo '
     <tr><td>'.$a.'</td></tr>
    ';
   //you can add as many columns as you wish

  }

  echo '</table>

I hope you picked understanding from this

Comments