Connecting to MySQL

 

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);