DEV Community

Darshan Hiranandani
Darshan Hiranandani

Posted on

Explain by Darshan Hiranandani : How do I connect to a MySQL database using PHP?

Hi Everyone, I'm Darshan Hiranandani, I'm Explaining how do connect to a MySQL database using PHP?

To connect to a MySQL database using PHP, you can use either the mysqli extension or the PDO (PHP Data Objects) extension. Below are examples for both methods:

Using mysqli Extension

<?php
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

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

// Close connection
$conn->close();
?>

*Using PDO Extension
*

<?php
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

// Close connection
$conn = null;
?>

Explanation
Database Credentials:

$servername: The hostname or IP address of the MySQL server.
$username: The username for the MySQL database.
$password: The password for the MySQL database.
$dbname: The name of the MySQL database you want to connect to.
Using mysqli:

Create a connection using new mysqli().
Check the connection with $conn->connect_error.
Close the connection with $conn->close().
Using PDO:

Create a new PDO instance with the DSN (Data Source Name), username, and password.
Set the error mode to PDO::ERRMODE_EXCEPTION to throw exceptions on errors.
Close the connection by setting the PDO instance to null.
Choosing Between mysqli and PDO
mysqli: Procedural and object-oriented interface. Supports only MySQL.
PDO: Object-oriented interface. Supports multiple database types (MySQL, PostgreSQL, SQLite, etc.). Provides a more flexible and secure way to interact with databases.
Both methods are widely used, but PDO is recommended for its flexibility and support for multiple database types.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay