👋 Hey there, PHP developer! If you’re just getting started with web development, one of the first things you’ll need to learn is how to connect MySQL database to PHP. PHP and MySQL are a popular combo for building dynamic websites and web applications. Whether you’re creating a simple contact form or a full-fledged CMS, connecting your PHP code to a database is essential.
In this beginner-friendly guide, we’ll walk you through the entire process—from setting up your environment to establishing a secure connection using MySQLi and PDO methods. We’ll also share helpful tips and best practices to make your development journey smooth and efficient.
Why Connect PHP to MySQL?
PHP is a server-side scripting language that excels in dynamic content. MySQL is a powerful, open-source relational database management system (RDBMS). When you connect the two, you create data-driven applications like:
- Blogs
- E-commerce platforms
- Contact forms
- Admin dashboards
Without a database connection, your app won’t be able to store or retrieve any user input or system data. So learning how to connect PHP to MySQL is a must.
Methods to Connect PHP to MySQL
There are two primary ways to establish a connection:
- MySQLi (MySQL Improved)
- PDO (PHP Data Objects)
Let’s explore both with examples.
1. Connecting PHP to MySQL Using MySQLi
🧰 What is MySQLi?
MySQLi stands for “MySQL Improved.” It’s a PHP extension designed to work with MySQL databases and supports both procedural and object-oriented approaches.
✅ Benefits of MySQLi
- Supports prepared statements (important for security)
- Procedural and OOP styles
- Slightly faster with MySQL databases
🔧 MySQLi Connection Example (Procedural)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
🔧 MySQLi Connection Example (Object-Oriented)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>
🔍 Explanation
mysqli_connect()
establishes the connection.- It returns a connection object on success, or
false
on failure. - Use
mysqli_connect_error()
to get the reason if the connection fails.
🧹 Closing the Connection
$conn->close(); // Object-oriented
// or
mysqli_close($conn); // Procedural
2. Connecting PHP to MySQL Using PDO
🧰 What is PDO?
PDO (PHP Data Objects) is a database access layer that provides a uniform method of access to multiple databases (not just MySQL).
✅ Benefits of PDO
- Supports multiple database systems (MySQL, PostgreSQL, SQLite, etc.)
- Better error handling using exceptions
- Supports prepared statements
- Object-oriented only
🔧 PDO Connection Example
<?php
$host = "localhost";
$dbname = "my_database";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// Set error mode
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
🧹 Closing the Connection
PDO doesn’t require a specific function to close the connection. It happens automatically when the script ends or the connection variable is set to null
:
$conn = null;
Handling Connection Errors
Handling errors is a key part of development. Both MySQLi and PDO provide ways to catch and handle these gracefully.
- MySQLi: Use
connect_error
ormysqli_connect_error()
- PDO: Use a
try-catch
block withPDOException
Always display generic messages to users and log detailed errors for yourself.
MySQLi vs PDO: Which One Should You Use?
Feature | MySQLi | PDO |
---|---|---|
Database Support | MySQL only | Multiple DBs |
API Style | Procedural & OOP | OOP only |
Named Placeholders | ❌ No | ✅ Yes |
Binding Input Values | ✅ Yes | ✅ Yes |
Performance | Slightly faster | Slightly slower |
Error Handling | Basic | Exception-based |
Recommendation: If you’re sticking to MySQL and like the procedural style, MySQLi is good. If you want flexibility and cleaner code with exception handling, go with PDO.
Best Practices for PHP-MySQL Connections
- ✅ Use prepared statements to avoid SQL injection.
- ✅ Keep database credentials in a separate config file.
- ✅ Close connections after operations.
- ✅ Use try-catch blocks when using PDO.
- ✅ Don’t expose error messages in production.
Common Connection Errors and Fixes
Error | Cause | Solution |
---|---|---|
Access denied for user | Wrong username/password | Double-check credentials |
Unknown database | Database name doesn’t exist | Create the DB or fix name |
Could not connect: timeout | Server not running or wrong host | Start MySQL server |
Call to undefined function | Extension not enabled in PHP | Enable MySQLi or PDO in php.ini |
🎯 Final Thoughts
Congratulations! 🎉 You’ve just learned how to connect a MySQL database to PHP using both MySQLi and PDO — a fundamental skill for any backend PHP developer. This is your first step toward building powerful, data-driven websites and applications.
Whether you’re creating a simple contact form or a full-blown CMS, understanding how to securely connect and interact with a database is crucial. Start with MySQLi if you’re a beginner, and consider switching to PDO as your project grows or when you need support for multiple databases.
Whichever method you choose, always use prepared statements to keep your application secure from SQL injection. Mastering these database interactions will unlock the full potential of PHP development!
Want to learn more about how PHP handles user input from forms? Check out our detailed guide on handling user input in PHP.
For official documentation and updates, visit the PHP Manual on MySQLi and PDO.
Leave a Reply