What is the best practice for handling database connections in PHP functions?
When working with database connections in PHP functions, it is best practice to establish the connection outside of the function and pass it as a parameter to the function. This helps to avoid opening and closing multiple connections within the same script, which can lead to performance issues and potential connection errors. By passing the connection as a parameter, you can reuse the same connection throughout your script, improving efficiency and maintainability.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Function that takes the database connection as a parameter
function fetchData($conn) {
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Process data here
}
} else {
echo "No results found";
}
}
// Call the function with the database connection
fetchData($conn);
// Close the database connection
$conn->close();