I've been working in a small page with some easy CRUD. The data I get from the database is getting shown on the page. But the way how I show the data feels a bit off. I guess it can be done in a much cleaner way, and really want to know how.
I do it as follows:
First: I require the necessary class, and call the function the the HTML file:
<?php
require 'classes/vacatureData.php';
$db = new database();
$db->listAllVacatures();
require 'templates/head.php';
require 'templates/vacatureOverzicht.php';
require 'templates/footer.php';
In my class I got a public variable public $listAllVacatures;
, which I use to store all the values which I retrieve from the database.
The method to retrieve the data from the database looks as following:
public function listAllVacatures() {
$sql = 'SELECT * FROM vacatures';
$stmt = $this->db->prepare($sql);
if($stmt->execute()) {
$vacatures = $stmt->fetchAll();
foreach($vacatures as $vacature){
$this->listAllVacatures .= "<p>";
$this->listAllVacatures .= "<a href='vacature.php?id=$vacature[0]'>$vacature[1]</a>";
$this->listAllVacatures .= " - <a href='delete.php?id=$vacature[0]'>delete</a>";
$this->listAllVacatures .= " - <a href=''>Edit</a>";
$this->listAllVacatures .= "</p>";
}
} else {
$e = $stmt->errorInfo();
echo $e[2];
}
$this->db = null;
}
As you can see I use a foreach to fill $listAllVacatures
with data, but also some HTML (Which i feel shouldn't be there, but right now I'm not quite sure how to organise this properly).
Then I got the template file which uses $listAllVacatures
:
<div class="container">
<p><h3>Vacatures:</h3></p>
<?php echo $db->listAllVacatures ?>
</div>
This all works fine, but like I said, it doesn't feel right to do it this way. But for now it's the best way I know.