How can one validate and sanitize user input in PHP to prevent SQL injection attacks?

To validate and sanitize user input in PHP to prevent SQL injection attacks, you can use prepared statements with parameterized queries. This helps separate the SQL query from the user input, preventing malicious SQL code from being executed. Additionally, you can use functions like mysqli_real_escape_string() to sanitize user input before using it in a query.

// Establish a database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Sanitize user input using mysqli_real_escape_string()
$username = mysqli_real_escape_string($conn, $_POST['username']);

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

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Handle the fetched data
}

// Close the statement and connection
$stmt->close();
$conn->close();