php-mvc
php-mvc copied to clipboard
DataBase & Controllers code
Hello,
I am a student and would like to retrieve information from my database to display in a view. I have been trying for 2 days without success. Here is my code:
Models -> Menu:
<?php
namespace App\Models;
use PDO;
class Menu extends \Core\Model
{
public static function getAllMenu()
{
$db = static::getDB();
$stmt = $db->query('SELECT id, dish_name, dish_content, dish_option, dish_price, dish_img FROM recette');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
Controllers -> Menu
<?php
namespace App\Controllers;
use \Core\View;
class Menu extends \Core\Controller
{
/**
* Show the index page
*
* @return void
*/
public $name;
public $content;
public $price;
public function indexAction($args)
{
$this->$args = [];
View::renderTemplate('Menu/index.phtml');
}
}
Views -> Menu (phtml)
<div class = "menu-wrapper" id="menu-wrapper">
<!-- Recettes -->
<div class="starters menu-restaurant">
<?php
echo 'Name:' . $args ['dish_name'];
?>
</div>
</div>
If someone to help me by telling me where the problem is coming from. I think it's from the Controllers. And how to display it in the view? Is this a return from a data table? Thanks for your help
Hi - if you're a student on the Udemy course, please ask any questions in the Q&A section there. As for your code, you need to call the model method from the controller, then pass that data to the view, e.g.
public function indexAction($args)
{
$this->$args = [];
View::renderTemplate('Menu/index.phtml', [
'data' => \App\Models\Menu::getAllMenu()
]);
}
Then in the view the data will be available in the data variable.
Thanks for your help. I'm not a Udemy student because I don't speak English very well, but I'll fix it.
If you still have a few minutes, I just changed the code and got a Fatal error
Message: 'Too few arguments to function App\Controllers\Menu::indexAction(), 0 passed and exactly 2 expected'
Stack trace:
#0 [internal function]: App\Controllers\Menu->indexAction()
#1 /Users/emerson/Documents_local/Sites/Projet 3WA/php-mvc-master/Core/Controller.php(45): call_user_func_array(Array, Array)
#2 /Users/emerson/Documents_local/Sites/Projet 3WA/php-mvc-master/Core/Router.php(121): Core\Controller->__call('index', Array)
#3 /Users/emerson/Documents_local/Sites/Projet 3WA/php-mvc-master/public/index.php(33): Core\Router->dispatch('menu')
#4 {main}
Thrown in '/Users/emerson/Documents_local/Sites/Projet 3WA/php-mvc-master/App/Controllers/Menu.php' on line 16```
The method doesn't have any arguments - try this:
public function indexAction()
{
// $this->$args = [];