PHP

Database Connectivity with MYSQL


 

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.


Here is the Explanation of its parameters 

<?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.


Way to connect to a MySQL database

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

 

Php mysqli_close():

We can disconnect the Mysql database connection using myqli_close() function.