What are the potential risks of using MySQL queries directly in PHP code without using prepared statements or parameterized queries?

Using MySQL queries directly in PHP code without prepared statements or parameterized queries can leave your application vulnerable to SQL injection attacks. To mitigate this risk, it is important to use prepared statements or parameterized queries to properly sanitize user input before executing 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 statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = "user123";
$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();