How to establish a database connection using PDO in PHP?

To establish a database connection using PDO (PHP Data Objects) in PHP, you need to follow these steps:

Step 1: Create a new instance of the PDO class. You need to pass the database connection details such as the database host, database name, username, and password as parameters to the constructor.

$host = "localhost"; $dbname = "database_name"; $username = "username"; $password = "password"; $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);

Step 2: Optionally, you can set some attributes for the PDO object, such as error mode and fetch mode. These attributes determine how PDO handles database errors and fetches data.

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

Step 3: You now have an active database connection with the PDO object stored in the variable $pdo. You can use this object to execute SQL queries and interact with the database.

Here's an example of executing a SELECT query:

$query = "SELECT * FROM users"; $stmt = $pdo->query($query); $resultSet = $stmt->fetchAll(); foreach ($resultSet as $row) { echo $row['username'] . "<br>"; }

Note: Make sure to replace the database connection details ($host, $dbname, $username, and $password) with your actual database information.

By following these steps, you can establish a database connection using PDO in PHP.