How can the variable $db be made accessible within a function in PHP?
To make the variable $db accessible within a function in PHP, you can use the 'global' keyword inside the function to access the variable from the global scope. By declaring $db as a global variable within the function, you can then use it as needed within the function's code block.
$db = new mysqli('localhost', 'username', 'password', 'database');
function myFunction() {
global $db;
// Now $db can be used within this function
$result = $db->query("SELECT * FROM my_table");
// Rest of the function code
}
Keywords
Related Questions
- What are the best practices for handling form data in PHP when transferring it between different scripts or websites?
- How can the provided code snippet for calculating a checksum in PHP be optimized or improved for better performance and accuracy?
- How can system dependencies impact the functionality of date-related functions in PHP, and how can they be mitigated?