• Thu, May 2025

How to Connect PHP to a MySQL Database (Step-by-Step)

How to Connect PHP to a MySQL Database (Step-by-Step)

Learn how to connect PHP to a MySQL database step-by-step using both MySQLi and PDO methods for beginners.

If you're building dynamic web applications with PHP, connecting to a MySQL database is one of the first and most essential steps. PHP offers two primary methods for connecting to MySQL:

  • MySQLi (MySQL Improved)
  • PDO (PHP Data Objects)

In this guide, we'll walk through how to connect PHP to a MySQL database using both methods—step by step—so you can decide which is best for your project.

Prerequisites

Before you begin, ensure you have the following:

  • A server with PHP and MySQL installed (e.g., XAMPP, MAMP, or a live server)
  • Access to phpMyAdmin or MySQL command line
  • Basic knowledge of PHP

Step 1: Create a MySQL Database

  1. Open phpMyAdmin (usually via http://localhost/phpmyadmin)
  2. Click "New" and create a new database, e.g., mydatabase
  3. Create a user and grant privileges (or use root for development)
  4. Note your credentials:
    • Hostname: localhost
    • Username: e.g., root
    • Password: e.g., '' (empty by default in XAMPP)
    • Database: mydatabase

Step 2: Connect Using MySQLi

Procedural MySQLi Example


<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";

$conn = mysqli_connect($servername, $username, $password, $database);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully using MySQLi (Procedural)";
?>

Object-Oriented MySQLi Example


<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";

$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully using MySQLi (OOP)";
?>

Step 3: Connect Using PDO


<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully using PDO";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Comparison: MySQLi vs PDO

FeatureMySQLiPDO
API StyleProcedural + OOPOOP only
Named Placeholders
Supports Multiple DBs❌ (MySQL only)✅ (MySQL, PostgreSQL, SQLite, etc.)
Security (Prepared Statements)
PerformanceFast for MySQLSlightly slower, more flexible

Use MySQLi if you’re only working with MySQL and want a simpler syntax.
Use PDO if you need flexibility to support multiple database types and want cleaner code with prepared statements.

Best Practices

  • Use environment variables to store DB credentials instead of hardcoding
  • Always use prepared statements to avoid SQL injection
  • Close connections when done (optional in PHP, but good practice)

Conclusion

Connecting PHP to a MySQL database is a core skill for web developers. Whether you choose MySQLi or PDO, both offer robust ways to interact with your database securely. Start small, use best practices, and build from there!

Need more help? Drop your questions in the comments or consult the PHP official docs.

 

Frequently Asked Questions (FAQ)

❓ Which method is better: MySQLi or PDO?

It depends. Use PDO for flexibility and cleaner syntax. Use MySQLi if you're sure you'll only use MySQL and want procedural options.

 

❓ Do I need to close the database connection in PHP?

PHP automatically closes the connection when the script ends. However, calling $conn->close(); or $conn = null; (for PDO) can be good practice in larger apps.

 

❓ Why am I getting "Connection failed" errors?

Check:

  • Your server is running (Apache + MySQL in XAMPP)
  • Your credentials are correct
  • The database name exists
  • The hostname is localhost unless using remote DB

 

❓ Can I switch between MySQLi and PDO later?

Yes, but their syntax is different, so you'd need to refactor your code accordingly.

 

❓ Is one more secure than the other?

Both support prepared statements, which protect against SQL injection. Use them properly, and both are secure.

Y2A Post

Discover the innovative work in AI-generated blogs, seamlessly blending technology with creativity. This unique approach not only offers fresh perspectives on various topics but also ensures that content is engaging and relevant.