In PHP, what are the advantages of using mysqli or PDO over mysql functions for database interactions?

Using mysqli or PDO over mysql functions in PHP for database interactions offers several advantages, including improved security through prepared statements to prevent SQL injection attacks, support for multiple database types, and better error handling capabilities. Additionally, both mysqli and PDO are more actively maintained and supported by the PHP community compared to the deprecated mysql functions.

// Example of using mysqli for database interactions
$mysqli = new mysqli("localhost", "username", "password", "database");

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

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

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

$mysqli->close();