How can SQL queries be efficiently integrated into PHP functions for template parsing?

To efficiently integrate SQL queries into PHP functions for template parsing, you can create a function that takes a SQL query as a parameter, executes the query, fetches the results, and returns them for parsing in the template. This allows for separation of concerns and better organization of code.

function executeSQLQuery($query) {
    // Connect to your database
    $conn = new mysqli("localhost", "username", "password", "database");

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

    // Execute the SQL query
    $result = $conn->query($query);

    // Fetch the results
    $data = array();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }

    // Close the connection
    $conn->close();

    // Return the data for parsing in the template
    return $data;
}

// Example usage
$query = "SELECT * FROM users";
$users = executeSQLQuery($query);

// Now $users contains the data from the SQL query for use in the template