PHP Connect to MySQL Server

The PHP mysqli_connect() function is used to connect to the MySQL server.

Open a Connection to MySQL Database Server

In order to access the data inside a MySQL database, you first need to open a connection to the MySQL database server. In PHP you can easily do this using the mysqli_connect() function. All communication between PHP and the MySQL database server takes place through this connection. The basic syntax of the mysqli_connect() function is given with:

mysqli_connect(host, username, password, dbname);

The parameters in the above syntax have the following meanings:

Parameter Description
Optional — All the parameters are optional
host Either a host name or an IP address
username The MySQL user name
password The MySQL password to get access
dbname The name of the MySQL database to use

The example below shows the mysqli_connect() function in action.

Example

Download
  • <?php
  • /* Attempt MySQL server connection. Assuming you are running MySQL
  • server with default setting (user 'root' with no password) */
  • $link = mysqli_connect("localhost", "root", "");
  •  
  • // Check connection
  • if($link === false){
  •     die("ERROR: Could not connect. " . mysqli_connect_error());
  • }
  • ?>
 

Note:The default username for MySQL database server is 'root' and there is no password. However to prevent your databases from intrusion and unauthorized access you should set password for MySQL accounts.


Closing the MySQL Database Server Connection

The connection to the MySQL database server will be closed automatically as soon as the execution of the script ends. However, if you want to close it earlier you can do this by simply calling the PHP mysql_close() function.

Example

Download
  • <?php
  • /* Attempt MySQL server connection. Assuming you are running MySQL
  • server with default setting (user 'root' with no password) */
  • $link = mysqli_connect("localhost", "root", "");
  •  
  • // Check connection
  • if($link === false){
  •     die("ERROR: Could not connect. " . mysqli_connect_error());
  • }
  •  
  • // Close connection
  • mysqli_close($link);
  • ?>
 
Close

Your Feedback:

 

We would love to hear from you! Please say something.