How can a connection to a database be established and maintained effectively in PHP scripts to ensure successful data retrieval and modification operations?

Establishing and maintaining a connection to a database in PHP scripts can be achieved effectively by using the PDO (PHP Data Objects) extension. PDO provides a consistent interface for accessing various databases, making it easier to switch between different database systems. To ensure successful data retrieval and modification operations, it is important to properly handle errors, close the connection after use, and use prepared statements to prevent SQL injection attacks.

// Establish a connection to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

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

// Perform database operations here

// Close the connection after use
$dbh = null;