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=utf8mb4supports Hindi and emojisERRMODE_EXCEPTIONturns errors into exceptions you can catchFETCH_ASSOCreturns 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.