What are the potential security risks associated with using raw user input directly in SQL queries in PHP?

Using raw user input directly in 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 query from the user input.

// Example of using prepared statements to prevent SQL injection

// Assuming $conn is the database connection

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

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

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

// Fetch 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();