What are the potential security risks associated with using MySQL queries directly in PHP code?

When using MySQL queries directly in PHP code, there is a risk of SQL injection attacks if user input is not properly sanitized. To mitigate this risk, it is important to use prepared statements with parameterized queries to prevent malicious SQL code from being injected into the query.

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

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

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();

// Get result
$result = $stmt->get_result();

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

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