What are some potential pitfalls of using the mysql_query function in PHP, and what are some recommended alternatives?

Using the mysql_query function in PHP is not recommended as it is deprecated and has security vulnerabilities such as SQL injection attacks. Instead, it is recommended to use prepared statements with either PDO or MySQLi to prevent these security risks and ensure better code maintainability.

// Using prepared statements with PDO
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();

// Using prepared statements with MySQLi
$mysqli = new mysqli("localhost", "username", "password", "mydatabase");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);