Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between mysqli::real_connect and new mysqli object in connecting database?

Tags:

php

mysqli

I'm using this method to connect to mysql db :

$this->_Con = new mysqli($this->_DB['Server'],$this->_DB['User'],$this->_DB['Pass'],$this->_DB['DB']);

What is the difference when I connect using this method:

$this->_Con = mysqli_init();
$this->_Con->real_connect($this->_DB['Server'],$this->_DB['User'],$this->_DB['Pass'],$this->_DB['DB']);
like image 733
Nikko Reyes Avatar asked Oct 04 '12 03:10

Nikko Reyes


People also ask

What is Mysqli :: Real_connect ():?

mysqli::real_connect -- mysqli_real_connect — Opens a connection to a mysql server.

What is the difference between Mysql_connect and mysqli_connect?

There are several important differences between the two libraries: Mysqli supports charsets, mysql does not. Mysqli supports prepared statements, mysql does not. Mysql does not support multiple statements, mysqli does.

What does New Mysqli return?

Return Values ¶ mysqli::__construct() always returns an object which represents the connection to a MySQL Server, regardless of it being successful or not. mysqli_connect() returns an object which represents the connection to a MySQL Server, or false on failure.


1 Answers

Its just another way of connecting to your database. If you use mysqli_init() it will initialize the mysqli object first. Then using the object you will call real_connect() to connect to the database. But when you use new mysqli() you are initializing the mysqli object by passing in the connection values as parameters, So it does initialization and connection at the same time.

Note: Calling the constructor with no parameters is the same as calling mysqli_init().

In your first case you are getting the connection object as the return value because you are calling mysqli() constructor with parameters. So you can run queries on it. But in your second case you need to store the connection like this,

$con = $this->_Con->real_connect($this->_DB['Server'],$this->_DB['User'],$this->_DB['Pass'],$this->_DB['DB']);

Then run queries on $con

like image 183
Deepak Avatar answered Oct 25 '22 17:10

Deepak