From 6704d044ee0e5ada36fc2f971b5f21caa71ae10f Mon Sep 17 00:00:00 2001 From: filippo.bertilotti <filippobertilotti@gmail.com> Date: Thu, 23 May 2024 10:30:46 +0200 Subject: [PATCH] creazione metodo che restituisce l'id del prodotto creato (fix delle doppie connessioni) (parte 131) --- src/App/Controllers/products.php | 2 +- src/App/Database.php | 15 ++++++++++----- src/Framework/Model.php | 4 ++++ 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/App/Controllers/products.php b/src/App/Controllers/products.php index bf0a304..b8c5144 100644 --- a/src/App/Controllers/products.php +++ b/src/App/Controllers/products.php @@ -44,7 +44,7 @@ ]; if($this->model->insert($data)) { - echo "record saved"; + echo "record saved, ID:" . $this->model->getInsertID(); } else { echo $this->viewer->render("shared/header.php", [ "title" => "New Product" diff --git a/src/App/Database.php b/src/App/Database.php index a239bdb..c39c393 100644 --- a/src/App/Database.php +++ b/src/App/Database.php @@ -5,7 +5,7 @@ use PDO; class Database { - + private ?PDO $pdo = null; public function __construct(private string $host, private string $name, private string $user, @@ -13,9 +13,14 @@ } public function getConnection(): PDO { - $dns = "mysql:host={$this->host};dbname={$this->name};charset=utf8;port=3306"; - return new PDO($dns, $this->user, $this->password, [ - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION - ]); + if ($this->pdo === null) { + $dns = "mysql:host={$this->host};dbname={$this->name};charset=utf8;port=3306"; + $this->pdo = new PDO($dns, $this->user, $this->password, [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION + ]); + } + + return $this->pdo; + } } \ No newline at end of file diff --git a/src/Framework/Model.php b/src/Framework/Model.php index 6bc892b..51f28c2 100644 --- a/src/Framework/Model.php +++ b/src/Framework/Model.php @@ -26,6 +26,10 @@ $parts = explode("\\", $this::class); return strtolower(array_pop($parts)); } + public function getInsertID(): string { + $conn = $this->database->getConnection(); + return $conn->lastInsertId(); + } public function findAll(): array|bool { $pdo = $this->database->getConnection(); -- Gitblit v1.8.0