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
- How does the choice between Variante 1 and Variante 2 impact the efficiency and effectiveness of data manipulation in PHP?
- What best practices should be followed when fetching data from a database in PHP?
- How can PHP beginners ensure that their scripts are secure and free from vulnerabilities, such as preventing SQL injection attacks or cross-site scripting (XSS) vulnerabilities?