What potential issues can arise when using mysql_query in PHP and how can they be avoided?

One potential issue that can arise when using mysql_query in PHP is the vulnerability to SQL injection attacks if user input is not properly sanitized. To avoid this, it is recommended to use prepared statements or parameterized queries with mysqli or PDO instead.

// Using prepared statements with mysqli
$conn = new mysqli($servername, $username, $password, $dbname);

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

$username = $_POST['username'];
$stmt->execute();
$result = $stmt->get_result();

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

$stmt->close();
$conn->close();