What are the best practices for establishing a database connection and querying data in PHP?

Establishing a database connection and querying data in PHP involves using the PDO (PHP Data Objects) extension for secure, efficient database access. To establish a connection, you need to create a PDO object with the database credentials. To query data, you can prepare a SQL statement, bind parameters if needed, execute the query, and fetch the results.

// Establishing a database connection
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

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

// Querying data
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$id = 1;
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($results as $row) {
    echo $row['username'] . '<br>';
}