In what ways can transitioning from using mysql_ functions to PDO or MySQLi in PHP improve the security and stability of a web application?

Transitioning from using `mysql_` functions to PDO or MySQLi in PHP can improve the security and stability of a web application by providing prepared statements to prevent SQL injection attacks, supporting parameterized queries for safer data handling, and offering better error handling capabilities. Additionally, PDO and MySQLi are more modern and actively maintained compared to the deprecated `mysql_` functions.

// Using PDO to connect to a MySQL database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}