What are potential security risks when using the mysql_query function in PHP, and how can they be mitigated?

Potential security risks when using the mysql_query function in PHP include SQL injection attacks. To mitigate this risk, you should use prepared statements or parameterized queries instead of directly inserting user input into SQL queries.

// Using prepared statements to mitigate SQL injection risk
$conn = new mysqli($servername, $username, $password, $dbname);

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

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

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

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

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

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