What is the best practice for passing database connection information to PHP functions?
When passing database connection information to PHP functions, it is best practice to use dependency injection. This means passing the database connection object as a parameter to the function that requires it, rather than relying on global variables or constants. This approach makes the code more modular, testable, and easier to maintain.
// Example of passing database connection information using dependency injection
function fetchData(PDO $db) {
$stmt = $db->query("SELECT * FROM table");
return $stmt->fetchAll();
}
// Create a PDO connection
$db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Call the function with the database connection passed as a parameter
$data = fetchData($db);
Related Questions
- What potential pitfalls should be avoided when connecting PHP with SQL databases?
- What are common issues when trying to extract ID3 tags from audio streams using PHP?
- What measures can be taken to prevent emails from being filtered by spam filters, such as Norton, due to missing or incorrect header parameters in PHP?