Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and MySQLi close()

Tags:

php

mysqli

I am new to MySQL and PHP and am attempting to make my own CMS to help make managing my websites easier. Can someone explain mysqli's close() function?

  1. Is it necessary?
  2. What exactly does it do?
  3. I heard that after PHP runs its script that it closes the connection, is that true?
  4. Lastly, is there a security issue when not closing your connection to the database?
like image 750
Theopile Avatar asked May 20 '10 17:05

Theopile


People also ask

What is close () in PHP?

The close() / mysqli_close() function closes a previously opened database connection.

How do you close a database in PHP?

To close the connection in mysql database we use php function conn->close() which disconnect from database. Syntax: conn->close();

Should I close MySQLi connection?

Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.

When should you close a connection in PHP?

PHP PHP MySQLi Close connection Use Case: If our script has a fair amount of processing to perform after fetching the result and has retrieved the full result set, we definitely should close the connection.


2 Answers

Is it necessary?

No, PHP will end your connection after it finishes running.

What exactly does it do?

The reverse of mysqli_connect() -- it closes the active DB connection.

I heard that after PHP runs its script that it closes the connection, is that true?

Yes, see the answer to "Is it necessary?"

Lastly, is there a security issue when not closing your connection to the database?

Nope, no security issue. The connection can't be hijacked by an outsider or anything like that.

However, since the number of total connections available is limited, freeing the resource the second you're done with it is considered polite to close it when you're done. This is likely why you've been told to close it when you're done.

like image 83
Amy B Avatar answered Oct 03 '22 11:10

Amy B


You need to close the Mysql session when you manual set variables @@session or non-defined (set to @@session).
for example

 $mysqli->query("SET @uuid=UUID()"); 

https://dev.mysql.com/doc/refman/5.1/en/set-statement.html

like image 42
TD_Nijboer Avatar answered Oct 03 '22 12:10

TD_Nijboer