What are the potential pitfalls of using mysql_query() in PHP for checking user credentials and how can they be avoided?

Using mysql_query() in PHP for checking user credentials is not recommended due to security vulnerabilities such as SQL injection attacks. To avoid this, it is recommended to use prepared statements with parameterized queries to securely interact with the database.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check user credentials using prepared statements
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);

$username = $_POST['username'];
$password = $_POST['password'];

$stmt->execute();

// Check if user credentials are valid
if($stmt->fetch()) {
    // User credentials are valid
    echo "Login successful";
} else {
    // User credentials are invalid
    echo "Login failed";
}

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