How can outdated MySQL functions be replaced with mysqli or PDO for improved security in PHP?

Outdated MySQL functions in PHP are vulnerable to SQL injection attacks and lack support for newer MySQL features. To improve security, these functions should be replaced with either mysqli or PDO, which provide better security features and support for prepared statements.

// Using mysqli to connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Using prepared statements to prevent SQL injection
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "example_user";
$stmt->execute();
$result = $stmt->get_result();

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

// Close statement and connection
$stmt->close();
$mysqli->close();