English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The mysqli_real_connect() function establishes a connection to the MySQL server
mysqli_real_connect()The function establishes a connection with the MySQL server and returns the connection as an object.
The difference between the mysql_connect() function and the one below is:
mysqli_real_connect() requires a valid object, which is created by mysqli_init().
Various connection settings can be set using mysqli_options().
Provide the flags parameter.
mysqli_real_connect($con,[$host, $username, $passwd, $dname, $port, $socket, $flags])
Serial Number | Parameters and Description |
---|---|
1 | con (optional) This is an object representing the connection to the MySQL Server. |
2 | host (optional) This indicates the hostname or IP address. If you setNull or localhost If this parameter is passed as a value, the local host is considered as the host. |
3 | username (optional) This indicates the username in MySQL. |
4 | passwd (optional) This indicates the password for the given user. |
5 | dname (optional) Set the default database for executing query statements. |
6 | port (optional) Specify the port of the MySQL server. |
7 | socket (optional) Specify the socket or named channel to be used. |
8 | flags (optional) Here you can set the connection parameters, which can be one of the following constants:
|
This function returns a boolean value, which istrue;If the connection fails, it isfalse.
This function was originally introduced in PHP version5introduced and can be used in all higher versions.
The following examples demonstratemysqli_real_connect()Function usage (procedural style)-
<?php $db = mysqli_init(); //Establish connection $con = mysqli_real_connect($db, "localhost", "root", "password", "test"); if($con){ print("Connection established successfully"); }else{ print("Connection failed "); } ?>
Output result
Connection established successfully
In object-oriented style, the syntax of this function is$con->real_connect();.The following is an example of this function in object-oriented style;
<?php $db = mysqli_init(); //Connect to the database $con = $db->real_connect("localhost", "root", "password", "test"); if($con){ print("Connection established successfully"); }else{ print("Connection failed "); } ?>
Output result
Connection established successfully
Open a new connection to the MySQL server:
<?php $connection_mysql = mysqli_init(); if (!$connection_mysql){ die("mysqli_init failed"); } if (!mysqli_real_connect($connection_mysql, "localhost", "root", "password", "mydb")){ die("Connection error: " . mysqli_connect_error()); }else{ echo "Connection successful"; } mysqli_close($connection_mysql); ?>
Output result
Connection successful