PHP MySQL Connect
Connecting PHP to MySQL database
🔌 Connecting to MySQL
PHP provides multiple ways to connect to MySQL databases. The mysqli extension is the modern, recommended approach offering both procedural and object-oriented interfaces for secure database connections.
<?php
// MySQLi Object-Oriented Connection
$servername = "localhost";
$username = "root";
$password = "";
$database = "mydb";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
$conn->close();
?>
Output:
Connected successfully!
Connection Methods
MySQLi (Recommended)
Modern, secure MySQL extension
PDO
Database-agnostic interface
MySQL (Old)
Deprecated - Don't use
Security
Always use prepared statements
🔹 MySQLi Object-Oriented Connection
The object-oriented approach is clean and modern, making your code easier to read and maintain. It's the most popular method among PHP developers today.
<?php
// Connection parameters
$servername = "localhost";
$username = "root";
$password = "";
$database = "mywebsite";
// Create connection object
$conn = new mysqli($servername, $username, $password, $database);
// Check if connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database!";
// Always close connection when done
$conn->close();
?>
Output:
Connected successfully to database!
🔹 MySQLi Procedural Connection
The procedural style uses functions instead of objects. It's simpler for beginners but less organized for larger projects.
<?php
// Connection parameters
$servername = "localhost";
$username = "root";
$password = "";
$database = "mywebsite";
// Create connection using function
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
// Close connection
mysqli_close($conn);
?>
Output:
Connected successfully!
🔹 PDO Connection
PDO (PHP Data Objects) works with multiple database types, not just MySQL. It's great if you might switch databases later.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "mywebsite";
try {
// Create PDO connection
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// Set error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully with PDO!";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// Connection closes automatically
?>
Output:
Connected successfully with PDO!
🔹 Connection Error Handling
Always check if your connection succeeds and handle errors gracefully to help with debugging:
<?php
$servername = "localhost";
$username = "root";
$password = "wrong_password"; // Intentional error
$database = "mywebsite";
$conn = new mysqli($servername, $username, $password, $database);
// Detailed error checking
if ($conn->connect_error) {
// Log error for debugging
error_log("Database connection failed: " . $conn->connect_error);
// Show user-friendly message
die("Sorry, we're having technical difficulties. Please try again later.");
}
echo "Connection successful!";
$conn->close();
?>
Output (with wrong password):
Sorry, we're having technical difficulties. Please try again later.
🔹 Reusable Connection File
Create a separate file for database connection that you can include in all your PHP files:
🔸 config.php (Connection File)
<?php
// config.php - Database configuration
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'mywebsite');
// Create connection
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
🔸 index.php (Using the Connection)
<?php
// Include the connection file
require_once 'config.php';
// Now you can use $conn in this file
echo "Database connected!";
// Your database queries go here...
$conn->close();
?>
Output:
Database connected!
🔹 Connection Best Practices
Security Tips:
- Never hardcode passwords: Use environment variables or config files
- Use prepared statements: Prevent SQL injection attacks
- Close connections: Free up server resources
- Handle errors properly: Don't expose sensitive information
- Use SSL/TLS: Encrypt database connections in production