What are the differences between using PDO and MSQLI APIs for database interaction in PHP?

When working with databases in PHP, you can choose between using PDO (PHP Data Objects) or MySQLi APIs for interacting with the database. PDO is more flexible and supports multiple database systems, while MySQLi is specifically designed for MySQL databases and offers procedural and object-oriented interfaces. PDO also provides a more secure way to prevent SQL injection attacks and supports prepared statements, making it a preferred choice for many developers.

// Using PDO to connect to a MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}