What potential pitfalls should be considered when using the mysql_query function in PHP?

One potential pitfall when using the mysql_query function in PHP is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, it is important to use prepared statements or escape user input before passing it to the query. Additionally, the mysql_query function is deprecated as of PHP 5.5.0, so it is recommended to use mysqli or PDO instead for improved security and functionality.

// Example of using prepared statements with mysqli to prevent SQL injection
$conn = new mysqli($servername, $username, $password, $dbname);

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

$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()) {
    // do something with the data
}

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