Skip to content
PHP Logo

How can PHP developers simplify their code and improve maintainability when handling MySQL queries in functions?

PHP developers can simplify their code and improve maintainability when handling MySQL queries in functions by using prepared statements to prevent SQL injection attacks and improve performance. By separating the database logic into reusable functions and properly escaping user inputs, developers can ensure their code is secure and easy to maintain.

php
// Function to execute a prepared statement query
function executeQuery($connection, $query, $params) {
    $stmt = $connection->prepare($query);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

// Example of using the executeQuery function
$connection = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$query = "SELECT * FROM users WHERE id = ?";
$params = [1];
$results = executeQuery($connection, $query, $params);