Connecting to a Database
A database connection in MVC is the process of establishing a secure link between your application and a database server, allowing the model layer to perform operations such as retrieving, inserting, updating, or deleting data.
Models in an MVC application handle both data and business logic, and they often need to communicate with a database. This connection allows models to retrieve, store, and update information as the application runs.
It is important to secure database access to protect sensitive data and prevent attacks such as SQL injection. Good practice includes using prepared statements and parameter binding, and storing database credentials in configuration files or environment variables instead of hard-coding them into the application.
Database.php
12345678910111213141516171819202122232425262728293031323334353637<?php // Database.php class Database { private $host = 'localhost'; private $db = 'mvc_app'; private $user = 'dbuser'; private $pass = 'dbpass'; private $charset = 'utf8mb4'; private $pdo; private $error; public function __construct() { $dsn = "mysql:host=$this->host;dbname=$this->db;charset=$this->charset"; $options = [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::ATTR_EMULATE_PREPARES => false, ]; try { $this->pdo = new \PDO($dsn, $this->user, $this->pass, $options); } catch (\PDOException $e) { $this->error = $e->getMessage(); // In production, do not display errors directly! die('Database connection failed.'); } } public function getConnection() { return $this->pdo; } }
This Database class uses PHP Data Objects (PDO) to create a secure connection to a MySQL database. With PDO, you get built-in protection against SQL injection through prepared statements, and the flexibility to switch database drivers if needed.
The connection is configured to throw exceptions on errors and return associative arrays, which makes error handling and data access more reliable. Database credentials are kept inside the class, so they can be managed or updated without affecting the rest of the application.
UserModel.php
12345678910111213141516171819202122<?php // UserModel.php require_once 'Database.php'; class UserModel { private $db; public function __construct() { $database = new Database(); $this->db = $database->getConnection(); } public function getAllUsers() { $stmt = $this->db->prepare('SELECT id, name, email FROM users'); $stmt->execute(); return $stmt->fetchAll(); } }
Separating the database connection logic into its own class makes your codebase easier to maintain and update. If you need to change database credentials, switch to a different database system, or update connection settings, you only need to modify the Database class. Models such as UserModel can focus on data-related operations, leading to cleaner, more modular, and more testable code.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you explain how prepared statements work in PDO?
What are some best practices for storing database credentials securely?
How does separating the database connection improve code maintainability?
Awesome!
Completion rate improved to 6.67
Connecting to a Database
Свайпніть щоб показати меню
A database connection in MVC is the process of establishing a secure link between your application and a database server, allowing the model layer to perform operations such as retrieving, inserting, updating, or deleting data.
Models in an MVC application handle both data and business logic, and they often need to communicate with a database. This connection allows models to retrieve, store, and update information as the application runs.
It is important to secure database access to protect sensitive data and prevent attacks such as SQL injection. Good practice includes using prepared statements and parameter binding, and storing database credentials in configuration files or environment variables instead of hard-coding them into the application.
Database.php
12345678910111213141516171819202122232425262728293031323334353637<?php // Database.php class Database { private $host = 'localhost'; private $db = 'mvc_app'; private $user = 'dbuser'; private $pass = 'dbpass'; private $charset = 'utf8mb4'; private $pdo; private $error; public function __construct() { $dsn = "mysql:host=$this->host;dbname=$this->db;charset=$this->charset"; $options = [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::ATTR_EMULATE_PREPARES => false, ]; try { $this->pdo = new \PDO($dsn, $this->user, $this->pass, $options); } catch (\PDOException $e) { $this->error = $e->getMessage(); // In production, do not display errors directly! die('Database connection failed.'); } } public function getConnection() { return $this->pdo; } }
This Database class uses PHP Data Objects (PDO) to create a secure connection to a MySQL database. With PDO, you get built-in protection against SQL injection through prepared statements, and the flexibility to switch database drivers if needed.
The connection is configured to throw exceptions on errors and return associative arrays, which makes error handling and data access more reliable. Database credentials are kept inside the class, so they can be managed or updated without affecting the rest of the application.
UserModel.php
12345678910111213141516171819202122<?php // UserModel.php require_once 'Database.php'; class UserModel { private $db; public function __construct() { $database = new Database(); $this->db = $database->getConnection(); } public function getAllUsers() { $stmt = $this->db->prepare('SELECT id, name, email FROM users'); $stmt->execute(); return $stmt->fetchAll(); } }
Separating the database connection logic into its own class makes your codebase easier to maintain and update. If you need to change database credentials, switch to a different database system, or update connection settings, you only need to modify the Database class. Models such as UserModel can focus on data-related operations, leading to cleaner, more modular, and more testable code.
Дякуємо за ваш відгук!