English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The mysqli_connect() function opens a new connection to the MySQL server.
mysqli_connect()The function establishes a connection to the MySQL server and returns the connection as an object.
mysqli_connect([$host, $username, $passwd, $dname, $port, $socket])
Serial number | Parameters and descriptions |
---|---|
1 | host (optional) This indicates the hostname or IP address. If theNullorlocalhostIf this parameter is passed as a value, the local host is considered as the host. |
2 | username (optional) This indicates the username in MySQL. |
3 | passwd (optional) This indicates the password for the given user. |
4 | dname (optional) This indicates the default database in which the query should be executed. |
5 | port (optional) This indicates the port number you want to connect to the MySQL Server. |
6 | socket (optional) Specify the socket or the named pipe to be used. |
If a connection to the MySQL server has been successfully established, the PHP mysqli_connect() function returns a connection object. If the connection fails, this function returns a boolean value.false.
This function was originally introduced in PHP version5introduced in and can be used in all higher versions.
The following examples demonstratemysqli_connect()Usage of the function (procedural style):
<?php $host = "localhost"; $username = "root"; $passwd = "password"; $dbname = "mydb"; //Establish Connection $con = mysqli_connect($host, $username, $passwd, $dbname); if ($con) { print("Connection established successfully"); } else { print("Connection failed "); } ?>
Output Result
Connection established successfully
In an object-oriented style, you can useNew mysqli()The connection is created by the constructor, as shown below:
<?php $host = "localhost"; $username = "root"; $passwd = "password"; $dbname = "mydb"; //Establish Connection $con = new mysqli($host, $username, $passwd, $dbname); if ($con-> connect_errno) { print("Connection failed"); } else { print("Connection established successfully"); } //Close Connection $con -> close(); ?>
Output Result
Connection established successfully
You can also call this function without passing any parameters, as shown below:
<?php //Establish Connection $con = @mysqli_connect(); if ($con) { print("Connection established successfully"); } else { print("Connection failed "); } ?>
Output Result
Connection Failed
Open a new connection to a MySQL server:
<?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); ?>
Output Result
Failed to connect to MySQL: Access denied for user 'root'@'localhost' (using password: YES)