What are best practices for handling database connections and queries in PHP functions?
When handling database connections and queries in PHP functions, it is best practice to establish a connection outside of the function and pass it as a parameter to the function. This helps in reusing the connection and also improves the performance of the application by reducing the overhead of establishing a new connection every time the function is called.
// Establish a database connection
$connection = new mysqli('localhost', 'username', 'password', 'database');
// Function to fetch data from database using the existing connection
function fetchData($connection) {
$query = "SELECT * FROM table";
$result = $connection->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Process data
}
} else {
echo "No records found";
}
}
// Call the function with the existing connection
fetchData($connection);
// Close the connection
$connection->close();