I have asked a few hours ago, how could I create an object for the connection on the database, and I have been advised, not to bother creating an object just for the connection. I think I did.... next step, was to display the content of a simple table to check it works, and again I am stuck, not seeing errors but "Connected successfully Chef Object ( )".
My project structure:
- Recipe book
- classes
- chef.php
- includes
- header.php
- footer.php
- db_connection.php
- index.php
- classes
This is my db_connection.php file, which I have placed in a folder called "includes":
//Database constants
defined('DB_SERVER') ? null : define('DB_SERVER', "localhost");
defined('DB_USER') ? null : define('DB_USER', "someuser");
defined('DB_PASS') ? null : define('DB_PASS', "somepass");
defined('DB_NAME') ? null : define('DB_NAME', "somedbname");
defined('DB_DRIVER') ? null : define('DB_DRIVER', "mysql");
try {
$conn = new PDO(DB_DRIVER . ":dbname=" . DB_NAME . ";host=" . DB_SERVER, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Then, I have, in chef.php:
class Chef {
public function display_chefs($sql) {
include 'includes/db_connection.php';
try {
return $conn->query($sql);
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return array();
}
return true;
}
}
I don't know much about object oriented, the point of this project is to learn. So, I have taken a function that I used in a procedural way to display content from a table (see code below):
public function display_chefs($sql) {
include 'includes/db_connection.php';
try {
return $conn->query($sql);
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return array();
}
return true;
}
And then, on index.php I am instantiating the chef object and trying to perform the query...
<?php require_once('includes/db_connection.php');
require_once('classes/chef.php');
include('includes/header.php');
$chef = new Chef;
$sql = "SELECT * FROM chefs";
$chef->display_chefs($sql);
print_r($chef);
include('includes/footer.php'); ?>
But as I said, the only thing appearing on index.php if I look at the browser is "Connected successfully Chef Object ()".
The data I want to pull is from the table called "chefs", which has a column "id", column "name" and column "country". Should this appear in the chef class somehow?
Thanks in advance :)