Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 16

PHP MySQL Connection with PDO

In this lesson: Connect PHP to MySQL with PDO, handle errors and run prepared queries safely — copy-paste code for XAMPP and live hosting. Connect now.

Connecting PHP to MySQL

Most real websites store data in a database. MySQL is the most common database used with PHP. To use it, PHP first connects to the database, then sends SQL queries to read or write data. The modern, safe way to do this in PHP is with PDO and prepared statements.

💡 Two rules: connect with PDO, and always use prepared statements for any query that includes user input.

Make a connection (PDO)

<?php
  try {
      $pdo = new PDO(
          "mysql:host=localhost;dbname=school",
          "root",   // username
          ""        // password
      );
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      echo "Connected!";
  } catch (PDOException $e) {
      echo "Failed: " . $e->getMessage();
  }
?>
Connected!

The connection string names the host and database. The try-catch catches problems (like a wrong password) so your page does not crash with a raw error.

Insert data safely

Use a prepared statement with placeholders, then pass the values separately.

<?php
  $sql = "INSERT INTO students (name, marks) VALUES (?, ?)";
  $stmt = $pdo->prepare($sql);
  $stmt->execute(["Aman", 88]);
  echo "Row added";
?>
Row added

The ? marks are placeholders. The real values ("Aman", 88) go in execute(), so they can never be mistaken for SQL — this stops SQL injection.

Fetch data

<?php
  $stmt = $pdo->query("SELECT name, marks FROM students");
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  foreach ($rows as $r) {
      echo $r["name"] . ": " . $r["marks"] . "\n";
  }
?>
Aman: 88

fetchAll(PDO::FETCH_ASSOC) returns every row as an associative array, so you read columns by name like $r["name"].

Why prepared statements

Never paste user input straight into SQL like this:

<?php
  // DANGEROUS - do not do this:
  $sql = "SELECT * FROM users WHERE name = '$name'";
?>

If $name contains SQL, an attacker can read or delete your data (SQL injection). Prepared statements keep the values separate from the query, which closes this hole completely.

Common mistakes

  • Building SQL by pasting input. Always use placeholders and execute().
  • No try-catch. Connection or query errors then crash the page with raw messages.
  • Wrong host or database name. Double-check the connection string details.
  • Forgetting FETCH_ASSOC. Set it to read rows cleanly by column name.

Summary

  • Connect PHP to MySQL with PDO, inside a try-catch.
  • Use prepared statements with ? placeholders for all user data.
  • Pass real values in execute() — never paste them into SQL.
  • Read results with fetch() or fetchAll(PDO::FETCH_ASSOC).
  • Prepared statements are your main defence against SQL injection.

Next, understand the choice in PDO vs MySQLi, or build full data operations with PHP CRUD.

Frequently Asked Questions

How do I connect PHP to a MySQL database?
Create a PDO object with your host, database name, username and password: new PDO("mysql:host=localhost;dbname=school", "root", ""). Wrap it in a try-catch to handle connection errors cleanly.
What is the difference between PDO and MySQLi?
Both connect PHP to MySQL. PDO works with many databases and has a clean, consistent style, while MySQLi works only with MySQL. PDO is usually recommended for new projects because of its flexibility and named parameters.
What is a prepared statement and why use it?
A prepared statement sends the SQL and the values separately, so user input can never be treated as SQL commands. This is the main protection against SQL injection and should be used for every query with user data.
How do I get results from a SELECT query?
After executing the statement, use fetch() for one row or fetchAll() for all rows. With PDO's FETCH_ASSOC mode you get each row as an associative array keyed by column name.
Why should I use try-catch with database code?
Database operations can fail — wrong password, server down, bad query. A try-catch lets you catch the error and show a friendly message instead of exposing a raw error to the user.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicPHP CRUD Operations Your progress: 16 / 50 (32%) · Lesson 17 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free