PHP & MySQLCore· 40 min read

Connecting PHP to MySQL (PDO)

Give your app a memory. Connect PHP to a MySQL database the modern, safe way — with PDO.

What you will learn

  • Connect to MySQL with PDO
  • Run a simple query
  • Handle connection errors

Connect with PDO

PDO (PHP Data Objects) is the modern, secure way to talk to a database. Before you can read or write any data, your script has to open a connection to MySQL. The flow is always the same:

  1. Gather the connection details: the host, the database name, the username and password.
  2. Wrap the attempt in a try block, because connecting can fail.
  3. Create a new PDO(...) object with those details — this opens the connection.
  4. Turn on error reporting so problems throw clear exceptions instead of failing silently.
  5. If anything goes wrong, the catch block shows the error message.
Connect to MySQL with PDO
<?php
  $host = "localhost";
  $db   = "codingclave";
  $user = "root";
  $pass = "";

  try {
    $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected!";
  } catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
  }
?>

The four variables hold the connection details (root with a blank password is the common XAMPP default). new PDO("mysql:host=$host;dbname=$db", $user, $pass) does the actual connecting — the first piece is the address of the database, then the login. The setAttribute(...) line tells PDO to throw an exception on any error, which is why we can catch failures. If the connection cannot be made, the catch runs instead.

Note: Output (in the browser): Connected! If the database name, username or password were wrong, you would instead see something like Connection failed: SQLSTATE[HY000] [1045] Access denied — the catch block turning a crash into a readable message.

Read data

Once connected, you can ask the database for data with a query. This reads every row from a users table and loops through the results:

Query and loop the results
<?php
  $stmt = $pdo->query("SELECT * FROM users");
  $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

  foreach ($users as $user) {
    echo $user["name"] . "<br>";
  }
?>

$pdo->query("SELECT * FROM users") sends the SQL to fetch all users and gives back a *statement* object. $stmt->fetchAll(PDO::FETCH_ASSOC) pulls every row into an array, where each row is an associative array (PDO::FETCH_ASSOC means "use the column names as keys"). The foreach then visits each row, and $user["name"] reads the name column.

Note: Output (in the browser, assuming three rows in the table): Asha Ravi Meera Each row came back as ["name" => ..., "email" => ...] — exactly the associative-array shape from the arrays lesson. That is why database rows and PHP arrays feel so natural together.

Note: You will need a users table — that is what the MySQL subject teaches. Learn SQL alongside this to get the full picture.

Q. What is PDO?

Answer: PDO (PHP Data Objects) is a secure, database-agnostic way to connect and run queries from PHP.

✍️ Practice

  1. Connect to a MySQL database with PDO (use try/catch).
  2. Query a table and loop the results.

🏠 Homework

  1. Create a database with a users table and list all users on a PHP page.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →