Establishing a connection between PHP and MySQL is a fundamental aspect of web development. PHP provides three primary methods for connecting to a MySQL database:
Procedural Style
<?php
$host = “localhost”;
$user = “root”;
$password = “”;
$dbname = “testdb”;
$conn = mysqli_connect($host, $user, $password, $dbname);
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Connected successfully!”;
?>
Object-Oriented Style
<?php
$host = “localhost”;
$user = “root”;
$password = “”;
$dbname = “testdb”;
$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
echo “Connected successfully!”;
?>
Using PDO (PHP Data Objects)
<?php
$host = “localhost”;
$dbname = “testdb”;
$user = “root”;
$password = “”;
try {
$conn = new PDO(“mysql:host=$host;dbname=$dbname”, $user, $password);
// Set Error Handling Mode
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo “Connected successfully!”;
} catch (PDOException $e) {
echo “Connection failed: ” . $e->getMessage();
}
?>
Summary
Method | Style | Security | Recommended? |
MySQLi | Procedural | Medium (OK) | ✅ Yes |
MySQLi | Object-Oriented | Medium–High | ✅✅ Best |
PDO | Object-Oriented | High (with prepared statements) | ✅✅✅ Best |