What are some best practices for handling database connections in PHP functions to prevent errors like "Undefined variable: db"?
When handling database connections in PHP functions, it is important to ensure that the database connection variable is properly defined and accessible within the function scope to prevent errors like "Undefined variable: db". One way to address this issue is to pass the database connection variable as a parameter to the function or use the global keyword to access the variable within the function.
// Define the database connection outside of the function
$db = new mysqli('localhost', 'username', 'password', 'database');
// Function that uses the database connection
function fetchData($db) {
// Use the $db variable within the function
$result = $db->query("SELECT * FROM table");
// Process the query result
return $result->fetch_assoc();
}
// Call the function with the database connection
$data = fetchData($db);