Should the PDO object be passed as a parameter to functions handling database queries in PHP, or is there a better approach?
When handling database queries in PHP using PDO, it is a good practice to pass the PDO object as a parameter to functions that need to interact with the database. This helps in maintaining a clean separation of concerns and allows for better reusability of code. Alternatively, you can create a database class or a database connection class that encapsulates the PDO object and handles database interactions internally.
// Example of passing PDO object as a parameter to a function handling database queries
function getUsers(PDO $pdo) {
$stmt = $pdo->query("SELECT * FROM users");
return $stmt->fetchAll();
}
// Create a PDO connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Call the function passing the PDO object
$users = getUsers($pdo);
Keywords
Related Questions
- What are the limitations of using PHP to display data from an Access database on a website accessed over VPN?
- What are some best practices for implementing and managing templates in PHP to ensure code readability and maintainability?
- How can PHP file upload functions be used to handle temporary and client-side file names?