corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-23 6704d044ee0e5ada36fc2f971b5f21caa71ae10f
creazione metodo che restituisce l'id del prodotto creato (fix delle doppie connessioni) (parte 131)
3 files modified
21 ■■■■ changed files
src/App/Controllers/products.php 2 ●●● patch | view | raw | blame | history
src/App/Database.php 15 ●●●●● patch | view | raw | blame | history
src/Framework/Model.php 4 ●●●● patch | view | raw | blame | history
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"
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;
    }
}
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();