What are the advantages of using MySQLi or PDO over the deprecated MySQL API in PHP for database interactions?

The advantages of using MySQLi or PDO over the deprecated MySQL API in PHP for database interactions include improved security through prepared statements and parameterized queries, support for multiple database systems, object-oriented approach for easier code maintenance, and better error handling capabilities.

// Using MySQLi for database interactions
$mysqli = new mysqli("localhost", "username", "password", "database");

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

$query = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$id = 1;
$query->bind_param("i", $id);
$query->execute();
$result = $query->get_result();

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

$mysqli->close();