The PHP mysqli_real_connect() function establishes a connection with the MYSQL server and returns the connection as an object.
The built-in PHP mysqli_real_connect() differs from the PHP mysqli_connect() in the following ways -
- PHP mysqli_real_connect() function needs a valid object which has to be created by the mysqli_init() function.
- It can be used with the built-in PHP mysqli_options() for setting various options for the connection.
- It has a flag parameter.
Syntax
mysqli_real_connect($con,[$host, $username, $passwd, $dname, $port, $socket, $flags] )
Parameter Details
Sr.No | Parameter & Description |
---|---|
1 | con(Optional) This is an object representing a connection to MySQL Server. |
2 | 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. |
3 | username(Optional) This represents a user name in MySQL. |
4 | passwd(Optional) This is represents the password to the given user. |
5 | dname(Optional) This represents the default database in which the queries should be performed. |
6 | port(Optional) This represents the port number at which you want to establish a connection to MySQL Server. |
7 | socket(Optional) This represents the socket that is to be used. |
8 | flags(Optional) An integer value representing different connection options this can be one of the following constants −
|
Return Value
PHP Version
Example1
<?php $db = mysqli_init(); //Creating the connection $con = mysqli_real_connect($db, "localhost","root","password","test"); if($con){ print("Connection Established Successfully"); }else{ print("Connection Failed "); } ?>
Output
Connection Established Successfully
Example2
<?php $db = mysqli_init(); //Connecting to the database $con = $db->real_connect("localhost","root","password","test"); if($con){ print("Connection Established Successfully"); }else{ print("Connection Failed "); } ?>
Output
Connection Established Successfully
Example3
<?php $connection_mysql = mysqli_init(); if (!$connection_mysql){ die("mysqli_init failed"); } if (!mysqli_real_connect($connection_mysql,"localhost","root","password","mydb")){ die("Connect Error: " . mysqli_connect_error()); }else{ echo "Connection was successful"; } mysqli_close($connection_mysql); ?>
Output
Connection was successful
Do feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Do follow us on our various social media handles available and also subscribe to our newsletter to get our tutorial posts delivered directly to your emails.
Thanks for reading and bye for now.