PHP mysqli_connect() Function
Definition and Usage
The mysqli_connect() function establishes a connection with MySQL server and returns the connection as an object.
Syntax
mysqli_connect([$host, $username, $passwd, $dname, $port, $socket] )
Parameters
| Sr.No | Parameter & Description |
|---|---|
| 1 |
host(Optional) This represents a host name or an IP address. If you pass Null or localhost as a value to this parameter, the local host is considered as host. |
| 2 |
username(Optional) This represents a user name in MySQL. |
| 3 |
passwd(Optional) This is represents the password to the given user. |
| 4 |
dname(Optional) This represents the default database in which the queries should be performed. |
| 5 |
port(Optional) This represents the port number at which you want to establish a connection to MySQL Server. |
| 6 |
socket(Optional) This represents the socket that is to be used. |
Return Values
If a connection got established successfully to the MySQL server. The PHP mysqli_connect() function returns the connection object. Incase of an unsuccessful connection this function returns the boolean value false.
PHP Version
This function was first introduced in PHP Version 5 and works works in all the later versions.
Example
Following example demonstrates the usage of the mysqli_connect() function (in procedural style) −
<?php
$host = "localhost";
$username = "root";
$passwd = "password";
$dbname = "mydb";
//Creating a connection
$con = mysqli_connect($host, $username, $passwd, $dbname);
if($con){
print("Connection Established Successfully");
}else{
print("Connection Failed ");
}
?>
This will produce following result −
Connection Established Successfully
Example
In object oriented style you can use the new mysqli() construct to create a connection as follows $minus;
<?php
$host = "localhost";
$username = "root";
$passwd = "password";
$dbname = "mydb";
//Creating a connection
$con = new mysqli($host, $username, $passwd, $dbname);
if($con->connect_errno){
print("Connection Failed ");
}else{
print("Connection Established Successfully");
}
//Closing the connection
$con -> close();
?>
This will produce following result −
Connection Established Successfully
Example
You can also invoke this function without passing any parameters as shown below −
<?php
//Creating a connection
$con = @mysqli_connect();
if($con){
print("Connection Established Successfully");
}else{
print("Connection Failed ");
}
?>
This will produce following result −
Connection Failed
Example
<?php
$connection_mysql = @mysqli_connect("localhost", "root", "wrong_password", "mydb");
if (mysqli_connect_errno($connection_mysql)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
echo ("Connection established successfully");
mysqli_close($connection_mysql);
?>
This will produce following result −
Failed to connect to MySQL: Access denied for user 'root'@'localhost' (using password: YES)