Connecting to MySql database by PHP mysqli. you need to use this code in your top of the PHP connection file. Or the best method creates a separate .php file to the common connection for all PHP database file instead of every page connection.

PHP MySQLi database connection

create a file – database_connection.php

<?php
  $servername = "localhost"; //your server name normaly its be localhost
  $username = "root"; // This is your database username.
  $password = ""; // This is your database password.
  $dbname = "databasename"; // This is your database name
  // Create connection
  $conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error()); 
?>

You can also using Obeject Oriented method of PHP mysql connection

create a file – database_connection.php

<?php
$servername = "localhost"; //your server name normaly its be localhost
$username = "root"; // This is your database username.
$password = ""; // This is your database password.
$dbname = "databasename"; // This is your database name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$conn->close();
?>

After creating this file you can include this file wherever you can need to connect the database by just using this code on before use.

include('db_connection.php');