How to properly set up a PDO connection

To set up a PDO connection, you will need to do the following:

  1. Install the PDO extension for your PHP installation, if it is not already installed.
  2. Create a new PDO object by passing in the appropriate connection string, username, and password as arguments to the constructor.
  3. Use the setAttribute() method to set any desired attributes for the connection, such as error handling or fetch mode.
  4. Use the query() or exec() method to execute SQL statements, or the prepare() method to create prepared statements for use with bound parameters.

Watch a course Learn object oriented PHP

Here is an example of a basic PDO connection:

<?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
  echo "Connection established.";
} catch (PDOException $e) {
  die("Error: Could not connect. " . $e->getMessage());
}

It's important to note that:

  • You should use try-catch block to handle connection errors
  • You should use a parameterized query to prevent SQL Injection
  • You should close the connection after you finish using it.