How can you properly connect to a database and retrieve data for use in PHP scripts?

To properly connect to a database and retrieve data for use in PHP scripts, you need to use the PDO (PHP Data Objects) extension. PDO provides a consistent interface for accessing different types of databases, making it a versatile and secure choice for database interactions in PHP.

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

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

// Retrieve data from the database
$stmt = $db->query('SELECT * FROM mytable');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results and do something with the data
foreach ($results as $row) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}