Zitat von
tlnewbie
[Einfaches Beispiel: wie mache ich eine Datenbankabfrage in einem Modul/ Controller?]
PHP-Code:
// src/Controller/ContentElement/ExampleElementController.php
namespace App\Controller\ContentElement;
use Contao\ContentModel;
use Contao\CoreBundle\Controller\ContentElement\AbstractContentElementController;
use Contao\CoreBundle\ServiceAnnotation\ContentElement;
use Contao\Template;
use Doctrine\DBAL\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @ContentElement(category="text")
*/
class ExampleElementController extends AbstractContentElementController
{
private $db;
public function __construct(Connection $db)
{
$this->db = $db;
}
protected function getResponse(Template $template, ContentModel $model, Request $request): ?Response
{
$newsRecords = $this->db->executeQuery("SELECT * FROM tl_news")->fetchAll();
if (!empty($newsRecords)) {
// Do something …
}
return $template->getResponse();
}
}
Lesezeichen