PHP Tutorial - PHP mysqli_connect() Function






Definition

The mysqli_connect() function opens a new connection to the MySQL server.

Syntax

mysqli_connect(host,username,password,dbname,port,socket);

Parameter

ParameterIs RequiredDescription
hostOptional.Host name or an IP address
usernameOptional.MySQL username
passwordOptional.MySQL password
dbnameOptional.Default database to be used
portOptional.Port number to attempt to connect to the MySQL server
socketOptional.Socket or named pipe to be used




Return

It returns an object representing the connection to the MySQL server.

Example

The following code opens a new connection to the MySQL server.


<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno($con)){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>