I'm new to doing things the oop way. Here's what I got.
First I've made a class that connects me to my database. Then I made a class to fetch the results from the database.
/engine/classes.php
class DB
{
public static function dbConnect()
{
$db = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if ($db->connect_error) {
die('A connection to the database cannot be made.');
}
}
}
class Blog
{
public function fetchBlog()
{
DB::dbConnect();
$results = array();
if ($blog = $db->query('SELECT * FROM blog')) {
if ($blog->num_rows) {
while ($row = $blog->fetch_object()) {
$results[] = $row;
}
$blog->free();
}
}
}
}
Then I have a core.php file where I include my classes.php file and instantiate these classes. Like so
/engine/core.php
require_once 'classes.php';
$con = new DB();
$con->dbConnect();
$blog = new Blog();
Then finally I have my index.php where the I'd like to echo the results I get. That looks like this
index.php
<?php include 'engine/core.php'; ?>
html stuff
<div id="blog">
<?php
$blog->fetchBlog();
if (!count($results)) {
echo'There are no blog posts at this time.';
} else {
foreach ($results as $r) {
echo'<div class="blogPost">
<em>', escape($r->postDate), '</em>
<h1>', escape($r->postTitle), '</h1>
<div>', escape($r->postBody), '</div>
</div>';
}
}
?>
</div>
I do have error reporting on and do not get errors on core.php or classes.php. However on my index.php page I am getting these errors
Notice: Undefined variable: db in C:\wamp\www\website\engine\classes.php on line 138
Fatal error: Call to a member function query() on a non-object in C:\wamp\www\website\engine\classes.php on line 138
How can I correct this? I assume I need a __construct somewhere in there and I also assume I'm not calling the dbConnect method correctly. I have tried a lot of things but listing them here would just be too much? Can anyone tell me what I am doing wrong?
Blogclass to make it locally accessible.