Skip to content
PHP Logo

How can code repetition be reduced and improved in PHP scripts that involve similar if-elseif-else blocks for database queries?

Code repetition in PHP scripts involving similar if-elseif-else blocks for database queries can be reduced and improved by creating a function that encapsulates the common logic for these queries. This function can take parameters to customize the query based on different conditions, reducing the need for duplicate code blocks.

php
function executeQuery($condition) {
    if ($condition === 'condition1') {
        // Query logic for condition1
    } elseif ($condition === 'condition2') {
        // Query logic for condition2
    } else {
        // Default query logic
    }
}

// Example usage
executeQuery('condition1');
executeQuery('condition2');