What is the best practice for passing a MySQL connection variable to functions in PHP?
When passing a MySQL connection variable to functions in PHP, it is best practice to use dependency injection. This means passing the connection variable as a parameter to the function that needs it, rather than relying on global variables. This approach makes the code more modular, testable, and easier to maintain.
// Establish MySQL connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Function that requires MySQL connection
function fetchData($conn) {
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
}
// Call the function with the MySQL connection
fetchData($conn);
// Close the MySQL connection
$conn->close();
Keywords
Related Questions
- What are the advantages of performing database sorting and selection operations within the database rather than in PHP?
- How can you improve the security of the PHP script to prevent directory traversal attacks or unauthorized file deletions?
- What are the differences between using the Options +Multiviews approach and the RewriteCond %{REQUEST_FILENAME}.php -f approach in hiding the .php extension in PHP URLs?