You connect PHP with a MySQL database in two main ways: with the MySQLi extension or with PDO (PHP Data Objects). Both need the same four things — the server name (usually localhost), the database username, the password and the database name. In this guide you will write both connections step by step, compare them, fix the most common errors and follow the best practices used in real projects.
What You Need Before Connecting
Before writing any code, make sure these three things are ready. First, a local server like XAMPP or WAMP should be installed and running, with Apache and MySQL started. Second, the database must already exist — create it in phpMyAdmin (open http://localhost/phpmyadmin, click New, give it a name and click Create). Third, you need a database user. On a local XAMPP setup the default user is root with an empty password, which is fine for learning but should never be used on a live website.
Method 1: Connect PHP with MySQLi
MySQLi is an extension made only for MySQL. It is simple and a good first connection to learn. Many developers store the four connection values as constants at the top of a file, like this:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'dbname');
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Check the connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
echo "Connected successfully";
Let us walk through it quickly. DB_SERVER is the hostname — localhost for your own computer, or the server IP or hostname given by your hosting provider. DB_USER is the database username and DB_PASS its password, which stays empty for the local root user. DB_NAME is the database you created in phpMyAdmin. The function mysqli_connect() uses these four values to open the connection, and mysqli_connect_errno() tells you if something went wrong so you can show the error instead of a blank page.
Method 2: Connect PHP with PDO (Recommended)
For modern PHP applications, PDO is the recommended approach. PDO works with many database types, not only MySQL, and it supports prepared statements in a very clean way. The connection is created inside a try-catch block so errors are handled properly:
<?php
$host = 'localhost';
$dbname = 'dbname';
$user = 'root';
$pass = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
The long string is called a DSN. It tells PDO the driver (mysql), the host, the database name and the character set. Always include charset=utf8mb4 so your site can store emojis and all languages correctly. Setting the error mode to ERRMODE_EXCEPTION means problems throw clear exceptions instead of failing silently, which saves hours of debugging.
MySQLi vs PDO: Which Should You Choose?
| Point | MySQLi | PDO |
|---|---|---|
| Databases supported | MySQL only | MySQL, PostgreSQL, SQLite and more |
| Prepared statements | Yes | Yes, with named placeholders too |
| Style | Procedural and object-oriented | Object-oriented only |
| Error handling | Manual error checks | Clean exceptions with try-catch |
| Best choice when | Small MySQL-only scripts | Most new projects |
Our honest advice: learn MySQLi first because it is simple, then move to PDO for real projects. Whichever you pick, use prepared statements for queries that include user input — they are your main defence against SQL injection attacks.
MySQLi in Object-Oriented Style
MySQLi also offers an object-oriented style, which many developers find cleaner once projects grow. The same four values are passed to the mysqli class instead of a function:
<?php
$conn = new mysqli('localhost', 'root', '', 'dbname');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
Both styles do the same job underneath. The procedural style reads like the classic tutorials, while the object-oriented style groups the connection and its methods into one object, so your code calls $conn->query() instead of passing the connection into every function. Pick one style per project and stay consistent — mixing both across files makes a project harder to read and maintain.
Connecting on a Live Server
On real hosting, three small things change. First, the hostname is usually still localhost, but some hosts give you a separate database server address — you will find it in your hosting control panel. Second, database names and usernames often carry a prefix from your hosting account, like myaccount_dbname, so copy them exactly from the panel instead of guessing. Third, the password is never empty: create a strong one when you create the database user in the panel. If your local code works but the live site shows "Access denied", the cause is almost always one of these three details.
Run Your First Query After Connecting
A connection alone does nothing visible, so let us fetch some rows with PDO:
<?php
$stmt = $pdo->query("SELECT id, name, email FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($users as $user) {
echo $user['name'] . " - " . $user['email'] . "<br>";
}
When a query includes a value that comes from the user, never paste that value directly into the SQL string. Use a placeholder instead:
<?php
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Common Connection Errors and How to Fix Them
| Error Message | Usual Cause | Fix |
|---|---|---|
| Access denied for user 'root'@'localhost' | Wrong username or password | Check the credentials, create a dedicated database user |
| Unknown database 'dbname' | Database does not exist or name is typed wrong | Create it in phpMyAdmin and match the exact name |
| Connection refused / No connection could be made | MySQL service is not running | Start MySQL from the XAMPP control panel |
| could not find driver | PDO MySQL extension is disabled | Enable pdo_mysql in php.ini and restart Apache |
Best Practices for Database Connections
Keep your connection code in one separate file, usually called config.php or db.php, and include it wherever you need the database. Never create a new connection inside every function. On a live server, create a separate database user for your website instead of using root, and give it only the permissions it needs. Keep the real password out of public folders and out of Git. Finally, when you finish a script that used MySQLi, you can close the connection with mysqli_close($con); with PDO, simply setting $pdo = null; closes it.
Once your connection works, you are ready to build something real with it. A great first project is a student registration and login system, which uses exactly this connection code plus forms and sessions.
Frequently Asked Questions
Which is better for beginners, MySQLi or PDO?
Start with MySQLi to understand the basics, then switch to PDO. PDO is the better long-term choice because it supports many databases and has cleaner error handling.
Why does PHP say "Connection refused"?
Almost always because the MySQL service is not running. Open the XAMPP control panel and start MySQL, then refresh the page.
What is the default MySQL username and password in XAMPP?
The username is root and the password is empty by default. This is only acceptable on your own computer, never on a live website.
Do I need to close the database connection?
PHP closes it automatically when the script ends, so it is optional for small scripts. Closing it yourself is still good practice in long or busy scripts.
What does charset=utf8mb4 do in the PDO connection?
It tells MySQL to use full UTF-8 encoding, so names in any language and even emojis are stored correctly instead of turning into question marks.
Conclusion
Connecting PHP to MySQL takes only a few lines: four values and one function with MySQLi, or a DSN and try-catch with PDO. Learn both, prefer PDO with prepared statements for real work, keep your credentials in one config file, and check the common errors table whenever a connection fails. With this one skill working, every PHP project with a database is now open to you.
Leave a Comment