PHP MySQL Connect
Before you can access data in a MySQL database, you must open a connection to the MySQL server. PHP offers two main ways to do this: MySQLi (MySQL Improved) and PDO (PHP Data Objects).
1. MySQLi vs. PDO
Both are used to communicate with MySQL, but they have different strengths:
- MySQLi: Works only with MySQL databases. It is often faster for MySQL-specific tasks and offers both object-oriented and procedural styles.
- PDO: Works with 12 different database systems (PostgreSQL, SQLite, etc.). If you switch your project to another database later, PDO makes the transition easier.
2. Open a Connection (MySQLi Object-Oriented)
This is the most common method for modern PHP applications using MySQL specifically.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
3. Open a Connection (PDO)
PDO uses a "DSN" (Data Source Name) and is typically wrapped in a try...catch block to handle connection errors gracefully.
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
4. Closing the Connection
The connection will be closed automatically when the script ends. However, you can close it manually to free up resources earlier.
// MySQLi
$conn->close();
// PDO
$conn = null;
Security Tip: When working on a real server, never use the "root" user with no password. Always create a specific database user with limited privileges for your application.