agyanadda@gmail.com

PHP MySQL Connect

PHP and MySQL 1 min read Updated Dec 1, 2026 Topic 29 of 36

PHP talks to MySQL with PDO (PHP Data Objects) or MySQLi. This tutorial uses PDO — it is secure, modern and works with many databases.

1. Create a database

In phpMyAdmin (XAMPP: http://localhost/phpmyadmin) create a database school and a table:

CREATE TABLE students (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(150) UNIQUE,
  course VARCHAR(50),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

2. Connect

$pdo = new PDO(
    'mysql:host=127.0.0.1;dbname=school;charset=utf8mb4',
    'root',
    '',
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
);
  • charset=utf8mb4 supports Hindi and emojis
  • ERRMODE_EXCEPTION turns errors into exceptions you can catch
  • FETCH_ASSOC returns rows as associative arrays

3. Keep it in one file

Put the connection in db.php and require it everywhere. Keep real passwords out of GitHub.

XAMPP's default user is root with an empty password — never use that on a live server.

Example

Example — Reusable connection file PHP
<?php
// db.php
$config = [
    'host' => '127.0.0.1',
    'db' => 'school',
    'user' => 'root',
    'pass' => '',
];

try {
    $pdo = new PDO(
        "mysql:host={$config['host']};dbname={$config['db']};charset=utf8mb4",
        $config['user'],
        $config['pass'],
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]
    );
} catch (PDOException $e) {
    error_log($e->getMessage());   // log the real error privately
    exit('Database connection failed. Please try again later.');
}

// test.php
// require __DIR__ . '/db.php';
// echo 'Connected! MySQL version: ' . $pdo->query('SELECT VERSION()')->fetchColumn();

If the details are correct, test.php prints "Connected! MySQL version: 8.x". On failure, the visitor sees a friendly message while the real error goes to the log.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which charset supports Hindi and emojis in MySQL?

Exercise 2 True / False

It is safe to show $e->getMessage() to visitors on a live site.

Exercise 3 Fill in the Blank

PDO::ATTR_ERRMODE => PDO::ERRMODE makes database errors throw exceptions.

Frequently Asked Questions

Both are fine. PDO supports many databases and has cleaner named parameters, so it is the common choice. Laravel uses PDO internally.