When using functions in PHP, what are the best practices for passing database connections as parameters?
When using functions in PHP that require database connections, it is best practice to pass the database connection as a parameter rather than creating a new connection within the function. This helps in reusability and ensures that the connection is properly managed and closed after its use.
// Example of passing database connection as a parameter in a function
function fetchData($dbConnection) {
$query = "SELECT * FROM table";
$result = mysqli_query($dbConnection, $query);
// Process the result
mysqli_close($dbConnection);
}
// Usage
$dbConnection = mysqli_connect("localhost", "username", "password", "database");
fetchData($dbConnection);
Related Questions
- Are there any potential pitfalls to be aware of when handling birthdates in PHP?
- What are some best practices for handling script execution times and server timeouts in PHP development, especially in the context of batch processing and image manipulation tasks?
- How can one ensure that a PNG image remains transparent and does not become distorted when using PHP functions like imagepng()?