In PHP, the mysqli extension provides both procedural and object-oriented ways to interact with MySQL databases. The mysqli_connect() function is a procedural approach to establish a connection with a MySQL database.
<?php
mysqli_connect(
$host, // The hostname or IP address of the MySQL server.
$username, // The MySQL user's username.
$password, // The password associated with the MySQL username.
$database, // The name of the MySQL database you want to connect to.
$port = 3306,// Optional. The port number to use when connecting to the database server.
$socket // Optional. The socket or named pipe to use when connecting to the database server.
);
?>
Note: Firstly, make sure you have the MySQLi extension enabled. You can do this by checking your PHP configuration or by running phpinfo() and looking for the MySQLi section.
<?php
$host = "localhost";
$username = "username";
$password = "password";
$database = "database_name";
// connection to database
$conn = mysqli_connect($host, $username, $password, $database);
// checking the connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully";
}
// Perform database operations here...
// closing connection
mysqli_close($conn);
?>
We can disconnect the Mysql database connection using myqli_close() function.