What are common pitfalls when using MySQL functions like mysql_db_query in PHP, and what are the recommended alternatives?

Common pitfalls when using MySQL functions like mysql_db_query in PHP include deprecated functions, lack of error handling, and vulnerability to SQL injection attacks. It is recommended to use MySQLi or PDO extensions in PHP for database operations as they provide better security, support for prepared statements, and are more up-to-date.

// Using MySQLi extension to perform database query
$mysqli = new mysqli("localhost", "username", "password", "database");

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

$query = "SELECT * FROM table_name";
$result = $mysqli->query($query);

if ($result) {
    while ($row = $result->fetch_assoc()) {
        // Process results
    }
} else {
    echo "Error: " . $mysqli->error;
}

$mysqli->close();