MySQL Connect with PHP

PHP mysqli_connect() function is used for opening a new MySQL server connection

Before using the MySql database, one must be aware of establishing the connections to MySql with PHP. If you have MySql and PHP installed on your system, you can use localhost for hostname and password will be none.

The function to connect to MySQL is called mysqli_connect(). This function returns a resource which is a pointer to the database connection.

The mysqli_connect function takes mainly four arguments; hostname, username, password, and database name.

Syntax:
mysqli_connect(hostname,username,password,dbname); 
ArgumentsDescription
hostnameEither a hostname or an IP address
usernameThe MySQL username
passwordMySQL user password
dbnameThe default database to be used when performing queries

Note: There are more two available parameters, but the above are the most important ones.

When the PHP script and MySQL are on the same machine, you can use localhost as the address, and the default password is none. If your MySQL service is running at a separate location, you will need to insert the IP address or URL in place of localhost.

Example:
<?php
// Database connection establishment
 $con=mysqli_connect("example.com","alex","qwerty","my_database");
 
// Check connection
 if (mysqli_connect_errno($con)) {
 echo "MySQL database connection failed: " . mysqli_connect_error();
 }
?> 

Close a Connection

When script execution ends, the connection will automatically close. To close the connection before, use mysqli_close() function:

Example:
<?php
// Create connection
 $con=mysqli_connect("example.com","alex","qwerty","my_database");
 
// Check connection
 if (mysqli_connect_errno($con)) {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

// Close Connection
 mysqli_close($con);
?> 

Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.