What are the security considerations when using user input in SQL queries in PHP and how can SQL injection vulnerabilities be prevented?

When using user input in SQL queries in PHP, it is important to sanitize and validate the input to prevent SQL injection vulnerabilities. One way to do this is by using prepared statements with parameterized queries, which separate the SQL code from the user input, making it impossible for an attacker to inject malicious code.

// Example of using prepared statements to prevent SQL injection

// Assume $conn is the database connection object

// Sanitize user input
$userInput = $_POST['input'];
$userInput = filter_var($userInput, FILTER_SANITIZE_STRING);

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

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

// Fetch the results
$result = $stmt->get_result();

// Process the results
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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