What are the potential security risks associated with directly inserting user input into SQL queries in PHP, and how can these risks be mitigated?

Potential security risks associated with directly inserting user input into SQL queries in PHP include SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To mitigate this risk, developers should use prepared statements with parameterized queries to sanitize user input before executing the SQL query.

// Using prepared statements to mitigate SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

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

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

// Set the user input and execute the query
$username = $_POST['username'];
$stmt->execute();

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

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