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.
<?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";
?>
<?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";
?>
We can close the connection with the following code.
// MySQLi Object-Oriented
$conn->close();
// MySQLi Procedural
mysqli_close($conn);