Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Connecting to a Database | Models
Quizzes & Challenges
Quizzes
Challenges
/
PHP MVC Development

bookConnecting to a Database

Note
Definition

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

Database.php

copy
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

UserModel.php

copy
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.

question mark

Which PHP extension is commonly used for secure database connections?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Suggested prompts:

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?

bookConnecting to a Database

Sveip for å vise menyen

Note
Definition

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

Database.php

copy
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

UserModel.php

copy
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.

question mark

Which PHP extension is commonly used for secure database connections?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 2
some-alt