Explain PHP Connect Database
Connecting to a database using PHP involves using either the mysqli
(MySQL Improved) extension or the PDO (PHP Data Objects) extension. Below, I will explain how to use both methods with examples.
Using mysqli
mysqli
is a relational database driver used in PHP to provide an interface with MySQL databases.
Example 1: mysqli
Procedural Style
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// Close connection
mysqli_close($conn);
?>
Example 2: mysqli
Object-Oriented Style
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 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
PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data.
Example: PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
try {
$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;
?>
Output
If the connection is successful, each of the examples will output:
Connected successfully
If the connection fails, you will get an error message, such as:
Connection failed: [error message]
Summary
mysqli
Procedural Style: Simpler and good for small projects.mysqli
Object-Oriented Style: More modern and recommended for object-oriented code.- PDO: More flexible and secure, supports multiple databases, and provides a consistent interface.
Choose the method that best fits your project's needs and coding style preferences.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.