What are the best practices for handling database connections in PHP functions?
When handling database connections in PHP functions, it is important to establish the connection outside of the function and pass it as a parameter to the function. This helps in reusing the same connection throughout the application and avoids opening and closing connections multiple times for each function call. Additionally, using prepared statements can help prevent SQL injection attacks.
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Function to fetch data from database
function fetchData($conn) {
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
}
// Call the function with the existing database connection
fetchData($conn);
// Close the database connection
$conn->close();