How can functions be encapsulated to enhance security in PHP applications, especially when interacting with databases?

To enhance security in PHP applications, functions can be encapsulated by creating wrapper functions that handle interactions with databases. These wrapper functions can include input validation, parameterized queries to prevent SQL injection attacks, and error handling to prevent sensitive information leakage. By encapsulating database interactions within these functions, the overall security of the application can be improved.

<?php

function connectToDatabase() {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database";

    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    return $conn;
}

function executeQuery($conn, $sql) {
    $result = $conn->query($sql);

    if (!$result) {
        die("Query failed: " . $conn->error);
    }

    return $result;
}

// Example usage
$conn = connectToDatabase();
$sql = "SELECT * FROM users";
$result = executeQuery($conn, $sql);

// Process the result...
?>