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

One potential security risk associated with using MySQL queries directly in PHP code is the vulnerability to SQL injection attacks. To mitigate this risk, developers should use prepared statements with parameterized queries to prevent malicious users from injecting SQL code 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 query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

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

// Set parameters and execute
$username = "admin";
$stmt->execute();

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

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Process data
}

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