How to perform a simple SELECT query using PDO in PHP?

To perform a simple SELECT query using PDO in PHP, you can follow these steps:

  1. Establish a PDO database connection:

    $dsn = "mysql:host=hostname;dbname=database_name"; $username = "username"; $password = "password"; try { $pdo = new PDO($dsn, $username, $password); } catch(PDOException $e) { echo "Database connection failed: " . $e->getMessage(); }
  2. Prepare the SELECT statement:

    $sql = "SELECT column1, column2 FROM table_name WHERE condition"; $stmt = $pdo->prepare($sql);
  3. Execute the SELECT statement:

    $stmt->execute();
  4. Fetch the results:

    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  5. Process the results:

    foreach($results as $row) { // Access specific column values using $row['column_name'] echo $row['column1'] . " " . $row['column2']; }
  6. Close the database connection:

    $pdo = null;

Make sure to replace 'hostname', 'database_name', 'username', 'password', 'table_name', 'column1', 'column2', and 'condition' with your specific values.