How do you connect MySQL database with PHP?

There are two methods to connect MySQL database with PHP. Procedural and object-oriented style.

To connect MySQL database with PHP, you can use the MySQLi (MySQL Improved) or PDO (PHP Data Objects) extension. Here’s how you can connect using both methods:

Using MySQLi extension:

php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
?>

Using PDO extension:

php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";

try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $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();
}
?>

Replace “localhost”, “username”, “password”, and “dbname” with your actual MySQL server details. Make sure that your MySQL server is running and accessible from your PHP environment. Additionally, it’s crucial to handle errors gracefully, as shown in the examples above.