Connect PHP to a database with PDO

8 steps · about 1 h 50 min · Beginner

  1. Enable PDO and the driver you need (reference, PHP Manual, 5 min)

    Check the extension and driver are loaded before you connect.

  2. Open and close a connection (reference, PHP Manual, 10 min)

    Covers DSNs, credentials and persistent connections.

  3. Make PDO throw exceptions on errors (reference, PHP Manual, 10 min)

    Exception mode stops silent failures.

  4. Prepare a statement with placeholders (reference, PHP Manual, 10 min)

    Named and positional placeholders keep data out of SQL.

  5. Fetch rows in the shape you need (reference, PHP Manual, 15 min)

    Fetch modes return arrays, objects or single columns.

  6. Read the practical PDO guide (article, PHP Delusions, 40 min)

    A detailed tutorial on correct, safe everyday PDO use.

  7. Follow PHP The Right Way on databases (article, PHP The Right Way, 10 min)

    Puts PDO in context with abstraction layers and structure.

  8. Use SQLite for local practice (reference, PHP Manual, 10 min)

    A file database lets you try PDO without a server.