Courses Job Ready Fresher Training AI for Class 7 to 12 Corporate Training Placements Tutorials
Free Learning Resources

IT Tutorials & Interview Prep

Free guides, interview Q&As, and job responsibility breakdowns — curated by industry veterans to help you crack MNC interviews

109+
Tutorial Articles
9
Topic Categories
100%
Free to Read
← Back to PHP

Connecting to MySQL

PHP Last Updated: Oct 17, 2025

Connecting to MySQL

In order to access the data in the MySQL database, first we need to connect to the database. Now, there are two types of approaches when connecting to the MySQL server.

  1. MySQLi Object-Oriented Method
  2. MySQLi Procedural Method

Connecting to Database using the MySQLi Object-Oriented Method

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

// Creating a connection
$conn = new mysqli($servername, $username, $password);

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

Connecting to Database using the MySQLi Procedural Method

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

// Create a connection
$conn = mysqli_connect($servername, $username, $password);

// Check the connection
if (!$conn) {
 die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Closing the Connection

We can close the connection with the following code.

// MySQLi Object-Oriented
$conn->close();

// MySQLi Procedural
mysqli_close($conn);

Want to practice these scenarios in a real IT environment? Our 45-Day Internship Program gives you hands-on experience with Active Directory, Ticketing Tools, and Networking.
Join the Internship →