What best practices should be followed when integrating MVC principles with MySQL database queries in PHP?
When integrating MVC principles with MySQL database queries in PHP, it is important to separate the database logic from the application logic. This can be achieved by creating a separate model class for handling database interactions. The model class should contain methods for querying the database and returning the results to the controller. This helps to maintain a clean separation of concerns and makes the code easier to test and maintain.
// Model class for handling database interactions
class UserModel {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function getUserById($id) {
$query = "SELECT * FROM users WHERE id = :id";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $id);
$stmt->execute();
return $stmt->fetch();
}
}
// Controller class for handling user requests
class UserController {
private $userModel;
public function __construct($userModel) {
$this->userModel = $userModel;
}
public function getUserById($id) {
$user = $this->userModel->getUserById($id);
// Do something with the user data
}
}
// Database connection
$db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$userModel = new UserModel($db);
$userController = new UserController($userModel);
$userController->getUserById(1);
Keywords
Related Questions
- What are the best practices for avoiding the error of modifying header information in PHP?
- In what situations would it be more beneficial to seek help in a Joomla forum rather than a PHP forum for multilingual content issues?
- How can the use of quotation marks in HTML attributes impact the functionality of links generated by PHP?