What are the best practices for structuring PHP code to avoid code duplication and improve readability, especially when dealing with database queries?

To avoid code duplication and improve readability when dealing with database queries in PHP, it is recommended to use functions or classes to encapsulate the database logic. By creating reusable functions or methods for common database operations, you can reduce code duplication and make your code more maintainable and readable.

<?php
// Function to connect to the database
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 to execute a query
function executeQuery($query) {
    $conn = connectToDatabase();
    $result = $conn->query($query);
    
    if (!$result) {
        die("Query failed: " . $conn->error);
    }

    return $result;
}

// Example of using the functions
$query = "SELECT * FROM users";
$result = executeQuery($query);

while ($row = $result->fetch_assoc()) {
    echo "Name: " . $row["name"] . "<br>";
}

$conn->close();
?>