What are the benefits of using mysqli or PDO over mysql functions in PHP?

Using mysqli or PDO over mysql functions in PHP is recommended because they provide better security by supporting prepared statements, which help prevent SQL injection attacks. Additionally, mysqli and PDO offer object-oriented interfaces, making it easier to work with databases and providing better error handling capabilities. Lastly, both mysqli and PDO support multiple database systems, allowing for easier migration if needed.

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

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

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

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

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