Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a MYSQLI connection be reopened WITHOUT instantiating a new object

Just a quick question here:

If I choose the object oriented style to interact with my database, ie...

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

And I then use $mysqli->close(); to close the connection at some point...

Can I reopen that connection by simply initiating another query $mysqli->query();, or do I have to instantiate a new MYSQLI object?

like image 720
Brownbay Avatar asked Aug 16 '10 02:08

Brownbay


People also ask

Why do MySQLi connections need to be closed?

Closing your connection allows for your resources to be reallocated.

What is the difference between MySQLi procedural and MySQLi object-oriented?

MySQLi provides a procedural way, much similar to the MySQL. This is the reason why developers coming from a MySQL background prefers using MySQLi. However, object-oriented programmers prefer PDO because of its compatibility with a large number of databases.

What does the MySQLi connect function return?

The mysqli_connect() function establishes a connection with MySQL server and returns the connection as an object.

Is MySQLi an OOP?

The mysqli extension features a dual interface. It supports the procedural and object-oriented programming paradigm. Users migrating from the old mysql extension may prefer the procedural interface. The procedural interface is similar to that of the old mysql extension.


2 Answers

No, you have to instantiate a new MYSQLI object. You can use the same variable $mysqli though but you have to write this code again:

 $mysqli = new mysqli("localhost", "my_user", "my_password", "world");
like image 145
shamittomar Avatar answered Sep 30 '22 03:09

shamittomar


Although it is not in the documentation, mysqli::connect() is a method, and you can use it to "reconnect" your object -appears to just be an alias for the constructor.

<?php
$host = '127.0.0.1';
$user = 'user';
$pass = 'pass';
$name = 'storage';

$mysqli = new mysqli($host, $user, $pass, $name);
// Do stuff...
$mysqli->close();
// Later on...
$mysqli->connect($host, $user, $pass, $name);
like image 26
jtrumbull Avatar answered Sep 30 '22 03:09

jtrumbull