Why is it recommended to use mysqli or PDO instead of mysql_* functions in PHP for database operations?

Using mysqli or PDO instead of mysql_* functions in PHP for database operations is recommended because the mysql_* functions are deprecated as of PHP 5.5 and removed in PHP 7. Additionally, mysqli and PDO offer more secure and flexible ways to interact with databases, including support for prepared statements, which help prevent SQL injection attacks.

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

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

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

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Process data
    }
} else {
    echo "0 results";
}

$mysqli->close();