What are the advantages of encapsulating SQL queries in PHP functions for database management and maintenance?
Encapsulating SQL queries in PHP functions for database management and maintenance helps improve code organization, readability, and reusability. It also enhances security by preventing SQL injection attacks and makes it easier to make changes to queries in one central location.
function executeQuery($sql) {
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute the query
$result = $conn->query($sql);
// Close the connection
$conn->close();
return $result;
}
// Example usage
$sql = "SELECT * FROM users";
$result = executeQuery($sql);
Related Questions
- What are the best practices for handling auto-increment primary keys in PHP when inserting data into a database?
- How can PHP developers ensure a seamless user experience when refreshing pages after executing code in a new window?
- What is the best practice for handling undefined offsets when working with arrays in PHP?