Before you can store or retrieve any data from a MySQL database, you must first establish a connection. PHP provides three main ways to do this: **MySQLi (Object-Oriented)**, **MySQLi (Procedural)**, and **PDO**.
To connect to a MySQL database, you generally need four pieces of information:
This is a modern approach that uses PHP's object-oriented features. It is clean and widely used.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully (Object-Oriented)";
?>
This approach uses standard functions instead of objects. It is often used by developers who prefer a more traditional programming style.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully (Procedural)";
?>
PDO is the most flexible method because it works with many different database systems (not just MySQL). It also uses exceptions for error handling, which is a modern best practice.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully (PDO)";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
While PHP automatically closes the connection when the script ends, it is good practice to close it manually to free up server resources as soon as you are done.
| Method | Syntax to Close |
|---|---|
| MySQLi (OO) | $conn->close(); |
| MySQLi (Proc) | mysqli_close($conn); |
| PDO | $conn = null; |
root and the password is "" (empty).
Now that we can connect to the server, let's learn how to create our first database using PHP in the **MySQL Create DB** lesson.