What are the potential security risks associated with directly embedding user input in SQL queries, as seen in the code snippet provided?

Directly embedding user input in SQL queries can lead to SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To prevent this, it is recommended to use prepared statements with parameterized queries. This approach separates the SQL query from the user input, preventing any malicious code from being executed.

// Using prepared statements to prevent SQL injection

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$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 parameter
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the parameter value and execute the statement
$username = $_POST['username'];
$stmt->execute();

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

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