How can PHP functions like ereg() be used to validate user input and prevent SQL injection attacks?

To prevent SQL injection attacks, user input must be validated before being used in SQL queries. PHP functions like ereg() can be used to ensure that input matches a specific pattern or format, thereby reducing the risk of SQL injection. By validating user input with functions like ereg(), developers can ensure that only safe and expected input is used in SQL queries, making the application more secure.

// Validate user input using ereg() to prevent SQL injection
$input = $_POST['user_input'];

if (ereg('^[A-Za-z0-9]*$', $input)) {
    // Input is safe, proceed with SQL query
    $sql = "SELECT * FROM users WHERE username = '$input'";
    // Execute SQL query
} else {
    // Input is not safe, handle error
    echo "Invalid input";
}