What are some potential security risks associated with directly inserting user input into SQL queries in PHP?

Directly inserting user input into SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To prevent this, you should always sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL code from the user input, preventing any malicious SQL code from being executed.

// Example of using prepared statements to prevent SQL injection

// Assuming $conn is a valid database connection

// Sanitize and validate user input
$userInput = $_POST['username'];

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

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

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

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

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