Does mysqli_close() do anything other than just destroying the object? - php

I know that using mysqli_close() is not needed, because PHP will destruct the object when the script is finished.
What I would like to know is why do we have such a function in the language in the first place? Does it do anything else, other than just destroying the object?
Is it equivalent to $conn = null; or unset($conn);?
Having limited C knowledge I looked into the source code to see what happens when I call this method, but I can't find anything other than just clearing internal pointers and calling efree().
Calling destructor on an object is never recommended, so why do we have a special exposed destructor for mysqli?

Remember that mysqli is an iteration on the mysql_* family of functions that are themselves little more than wrappers around the C Connector Library for MySQL. mysql_close is one such function, and naturally became mysqli_close in the "improved" API.
There are some situations where you'd want to force-close something immediately rather than waiting for the garbage collector to get around to it and automatically release the resource.
PDO, which is a better API all-around and doesn't deal with MySQL exclusively, has some notes on when a connection will actually be closed:
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
Tracking down those references can be annoying so it's actually nice that mysqli has a "just close it, don't care" function for those situations where that matters.

Related

mysqli object is already closed [duplicate]

I'm trying to pass a session with mysqli connection for multiple queries on the site, but when I try to do a query it outputs a warning "Couldn't fetch mysqli"
$_SESSION['db']=new mysqli($host,$username,$password,$db);
Is it impossible to pass a mysqli connection reference thru session? is there a different method to use?
Yes, it is explicitly impossible.
See PHP Documentation here mentioning in a highlighted Warning: "Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object)."
MySQL connections are one such kind of resource.
You have to reconnect on each page run.
This is not as bad as it sounds if you can rely on connection pooling via mysql_pconnect(), but first see more background info on mysql_pconnect() in this article.
Database connections are resources and can't be stored in a session. You'll have to rebuild the connection in every page, or use a persistent connection (PHP 5.3+).
Yeah - you can't pass it through a session. The handle is specific to the request. You might be able to put it in a shared resource like memcache, and fetch the handle when you need it.
However, if your using connection pooling, grabing a new handle when you need (and closing it when your done) isn't a large performance hit.
Always depends on your needs, but yeah, I'd either:
Create a new handle when you need it /per request/ (turn on connection pooling)
Stick the dbhandle in memcache

Reusing a PDO connection after execute?

I would like to know if it's correct to re-use a PDO db connection multiple times ?
For example, I set it up in my controller then pass it as a parameter in a constructor of a class, is it correct to call the same connection (by using a function like get_Database) thoughout all my functions in the class and even pass it as a parameter in another class construct to continue working with the same connection ?
Or should I reopen a connection at some point ?
I was able to get it working by simply passing it around, however I am not quite sure if this would be performing well when going live.
Yes, you should reuse the connection.
Or should I reopen a connection at some point ?
The only reason to open a new connection is if connecting to another database. Otherwise, throughout a single script only one connection should be used.
To achieve this it is important to try and avoid using a static singleton throughout your application, rather learn about dependency injection to design your code to share the same PDO instance to every function or class that needs it.
however I am not quite sure if this would be performing well when going live.
As commented, if you reopen a connection often, it will be a lot slower.
There are many dependency injector's out there, and it is almost certainly a matter of opinion, but I like Auryn. Learning about it should help you design code where it is easier to share a single PDO instance, amongst others.
Yes, this is OK and it is better than connecting to the database many times.
The documentation even suggests to use the opened connection between calls to your php script / application:
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

what is the downside of not closing a mysql connection in php script?

I am accessing a database in a php script by establishing a connection using mysqli_connect function. I observe it is not mandatory to close the connection at the end of the script.
What are the implications of not using mysqli_close() in a connection script created to access mysql database in php?
If you are using cgi, then it is not necessary to close your mysql connections since they close automatically at the end of script execution.
From the documentation:
Note: The link to the server will be closed as soon as the execution
of the script ends, unless it's closed earlier by explicitly calling
mysql_close().
Although it is considered a good practice to close your connection.
If you close the connection yourself:
You have to check the value of $_connected for every single query. This means PHP has to check that the variable $_connected A) exists
B) is a boolean and C) is true/false.
You have to call your 'disconnect' function, and function calls are one of the more expensive operations in PHP. PHP has to check that
your function A) exists, B) is not private/protected and C) that you
provided enough arguments to your function. It also has to create a
copy of the $connection variable in the new local scope.
Then your 'disconnect' function will call mysql_close() which means PHP A) checks that mysql_close() exists and B) that you have provided
all needed arguments to mysql_close() and C) that they are the correct
type (mysql resource).
So if you are not using persistent connections, your MySQL connection will be closed at the end of the page execution. So you dont have to bother about that. And hence no downsides.
If you're fairly sure you're not going to use the connection again, or don't have a class that manages your open connections, closing is good practice. A couple reasons:
If you're looping or something over something that creates connections without closing prior ones, you could eat up all your available DB connections based on whatever limit is set on the sql servers side. Typically this limit is for everyone not per host, so you could prevent others from connecting as well.
From Zend (maybe dated): Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster.

Is it necessary to close PDO connections

I noticed there is no close function for PDO. Should I close the connection or is it unnecessary for PDO?
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
http://php.net/manual/en/pdo.connections.php
So the answer is no, you don't need to do anything unless you need to explicitly close the connection during the script execution for whatever reason, in which case just set your PDO object to null.
This question is depending a bit on the type of project and the type of connection.
In almost all of my projects I never manually close the connection. In PHP the connection (unless it is a persistent connection) will only be open during the request. So manually closing it is pretty useless anyway.
When looking at my projects where there was no persistent connection it would have been very hard to know when to manually close the connection either way. Once a project gets larger than a couple of files (and the individual components have no idea about eachother like they should) it becomes very hard to know when the connection will still be needed.
And opening the connection again when needed is waay more expensive than just leaving it open during the request.
Something though when working with persistent connection there will be situations where you will want to manually close the connection.
So to answer your question:
I noticed there is no close function for PDO.
You can nullify the object reference (and all references to the object) to manually close the connection in PHP.
Should I close the connection or is it unnecessary for PDO?
In most situations it is not necessary.
From the PDO's connection page
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object.
If you don't do this explicitly, PHP will automatically close the connection when your script ends.
EDIT
I'd rather use persistent connection. Though, it's a good practice to close all connections at the end of the script.

In php how to do session instances?

I'm quite new on php and am trying to learn it.
My question is rather simple but I've been a bit lost while googling for it.
I just want to create an object to manage the database connection. I already did the object and now the problem I'm facing is:
How do i keep it instanced to a session? (So that i don't need to open/close the connection to the database on every page load) And how do I call it afterward?
Are there any way to declare a destroyer, so that when the instance is dying, the connection to the database gets closed?
If you define a __destruct() method on your object, it'll get called when the object is about to be destroyed. You can use this to close your database connection.
You can also use __sleep() and __wakeup() for serializing your objects. They'll get called automatically upon serialization and unserialization. You could use these methods to connect and disconnect as required.
I hate to answer by refuting the question but I think you are going about resolving the problem in the wrong way here.
Rather than worrying about the connection being opened/closed I would suggest using caching, indexing, etc. to solve performance problems when they arise rather than being concerned about the resources involved in establishing a connection.
If you are really concerned about performance why not cache the affected pages and avoid using the database connection at all?
I think you could get the desired effect with this function (don't use this myself, assuming mysql) but be sure to read the comments:
http://www.php.net/mysql-pconnect
I don't think you want to start using sleep/wakeup techniques as to get this working as I understand it would involve creating a whole bunch of separate threads each with its own database connection which will just sap your resources and produce the opposite of the intended effect.

Categories