What are some best practices for handling different formats of data in a database query using PHP and RegEx?

When handling different formats of data in a database query using PHP and RegEx, it's important to sanitize and validate the input to prevent SQL injection attacks and ensure data integrity. One way to achieve this is by using regular expressions to match and extract specific patterns from the input data before executing the query.

// Example of handling different formats of data in a database query using PHP and RegEx
$input = $_POST['input_data']; // Assuming input data is coming from a form POST request

// Validate and sanitize the input data using RegEx
if (preg_match('/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/', $input)) {
    // Input data is in the format "dd-mm-yyyy"
    $formatted_input = date('Y-m-d', strtotime(str_replace('-', '/', $input)));
} elseif (preg_match('/^[A-Za-z0-9\s]+$/', $input)) {
    // Input data contains only alphanumeric characters and spaces
    $formatted_input = mysqli_real_escape_string($conn, $input); // Assuming $conn is the database connection
} else {
    // Handle other formats or invalid input data
}

// Execute the database query using the sanitized and formatted input
$query = "SELECT * FROM table WHERE column = '$formatted_input'";
$result = mysqli_query($conn, $query);

// Process the query result as needed