How can PHP developers optimize their code by reducing repetition and improving code readability when performing database query checks for different values in multiple tables?

PHP developers can optimize their code by creating a reusable function that handles database query checks for different values in multiple tables. By creating a function that accepts parameters such as table name, column name, and value to check, developers can reduce repetition and improve code readability. This function can be called whenever a query check is needed, making the code more concise and maintainable.

<?php
// Function to perform database query checks for different values in multiple tables
function checkValueExists($tableName, $columnName, $value) {
    $query = "SELECT COUNT(*) FROM $tableName WHERE $columnName = :value";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':value', $value);
    $stmt->execute();
    
    return $stmt->fetchColumn() > 0;
}

// Example usage
if (checkValueExists('users', 'email', 'example@email.com')) {
    echo 'Email already exists in users table';
}

if (checkValueExists('products', 'name', 'Product A')) {
    echo 'Product A already exists in products table';
}
?>