How can input validation and sanitization be implemented in PHP to prevent SQL Injection attacks?

To prevent SQL Injection attacks in PHP, input validation and sanitization can be implemented by using prepared statements with parameterized queries. This involves separating the SQL query from the user input, which helps to prevent malicious SQL code from being executed. Additionally, input validation can be done by checking the type and format of user input before passing it to the database query.

// Example of implementing input validation and sanitization in PHP to prevent SQL Injection attacks

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// User input
$userInput = $_POST['user_input'];

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the parameter
$stmt->bindParam(':username', $userInput, PDO::PARAM_STR);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results
foreach ($results as $row) {
    // Output the data
    echo $row['username'] . "<br>";
}