I’m stuck at ch. 8 of PHP & MySQL: Novice to Ninja.
I’m unable to get the functions from my functions class to run in the controller. The book has you put the code for your joke list (and other pages) into a class so all the pages on the site can be run on a single page. Our tables are set up in another class which is passed the connection to the database.
class JokeController {
private $authorsTable;
private $jokesTable;
public function __contruct($jokesTable, $authorsTable){
$this->jokesTable = $jokesTable;
$this->authorsTable = $authorsTable;
}
public function list() {
$result = $this->jokesTable->findAll(); //Problem running this function
$jokes =[];
foreach ($result as $joke){
$author = $this->authorsTable->findById($joke['authorid']);
$jokes[] = [
'id' => $joke['id'],
'joketext' => $joke['joketext'],
'jokedate' => $joke['jokedate'],
'name' => $author['name'],
'email' => $author['email']
];
}
$title = 'Joke List';
$totalJokes = $this->jokesTable->total();
return ['template'=>'jokes.html.php',
'title'=>$title,
'variables'=> [
'totalJokes'=>$totalJokes,
'jokes'=>$jokes
]
];
}`
I get a fatal error when this tries to run. From what I could find on stack overflow this is because the connection isn’t being correctly used. I’m using PHP 7.1.9
<?php
$pdo = new PDO('mysql:host=localhost;dbname=nov2ninja;charset=utf8','jokeUser','mypassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
The jokeController class vars and contructor
class JokeController {
private $authorsTable;
private $jokesTable;
public function __contruct($jokesTable, $authorsTable){
$this->jokesTable = $jokesTable;
$this->authorsTable = $authorsTable;
}
And lastly the DatabaseTable.php vars and constructor
<?php
class DatabaseTable{
public $pdo;
private $table;
private $primaryKey;
public function __construct(PDO $pdo, string $table, string $primaryKey){
$this->pdo = $pdo;
$this->table = $table;
$this->primaryKey = $primaryKey;
}
The functions work fine on their own but don’t work at all when run from an external object like jokeController. Thanks for helping me out! Other than this I love the book so far, it’s really helpful!