mysqli object is already closed [duplicate] - php

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

Related

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.

How to organize the handling of database connections within functions?

When I was writing PHP code with PDO and MySQL, I would always create connections when I needed them within functions like so:
result pseudo_function() {
create and open connection
do stuff
close connection
return result
}
Now, I started programming in C, I have seen that pointers are an interesting way to pass the entire connection as parameter to the function. I was wondering if it would be better to pass the connections between functions until the entire user request is served.
To clarify: For one user request, there could be 1-5 calls to a function that then opens a database, fetches data, does something, closes and returns.
Also does it make a difference performance wise if you keep a connection opened?
The "standard idiom" for most PHP code I've seen seems to be "open the connection, and leave it open".
php.net seems to be down at the moment, but these two links might be of interest:
http://php.net/manual/en/function.mysql-pconnect.php
http://php.net/manual/en/mysqlnd-ms.pooling.php
If you're running Apache, perhaps mod_dbd might be a good solution:
http://httpd.apache.org/docs/2.2/mod/mod_dbd.html
Here's a good discussion on the implications of not closing your connections:
Is it totally reckless to leave mysql connection open through a page?
It's better to keep a connection open and perform 5 operations on that connection than opening a new connection every time.
You can also lazy-load your database with a singleton repository pattern; the repository only opens a connection once, upon next invocations it will return a cached result.
If you develop web applications with PHP, it's common (and I suppose the most efficient way) to open the database connection once and close it when the script terminates. Keeping a connection open while other stuff is done does not really produce any overhead or require any actions at all, but reconnecting every time does.

MySQL database connection not closed: what will happen?

I am using PHP to query the MySQL database on my website. Please answer the following questions:
What will happen if I don't use mysql_close() when I am done with querying the database in the end? The connection will remain open? If yes then upto how much time? If no then why?
If I open and close a connection to MySQL at several places in a
webpage, how is the performance affected? i.e. connection is made again everytime some access to database is required on a single webpage.
How is mysql_close() related to performance? Should I open a new connection everytime some access to database is required OR should I keep only one connection and close it in the end?
If I don't close the connection, then if the user is trying to
access some data again, will the new connection be used or the old
open connection will be used?
It will automatically close when the PHP script is done running during destruct phase.
Performance will negatively be affected. Opening a new socket (especially to an external database server) is more expensive and time consuming than just keeping a pointer to the current connection in memory.
See answer no. 2
The access to the data will be performed by a new PHP request. Hence, you will have a new database connection. No problems there.
I'd advise to open your database connection during construct phase, re-use that connection during the entire execution of your script (if it's OO based, assign a class variable for your database connection and use $this->db during the entire script), and close it during destruction (or don't bother at all closing it, as it will be closed anyway, even when not declared specifically).
From php.net :
Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
for performance it depends on situations, how long it is used, for how long it is idle and so on (e.g. long execution). In most cases, there is singleton pattern by which you have one open connection, and make all queries with that open handle. But it's not true all in all, as mysql_connect itself is kind of supports that:
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters.
So basically, mysql_close is not very needed when it comes to short running scripts.
There is negligible performance loss to close a connection, compared to the resource usage of keeping it open when you don't need it. Better to close a connection as soon as you're done with it, and open it again when you need to.
If you use non-persistent connections all opened MySQL connections will be automatically closed when the PHP script finishes execution.

Reusing Ajax Established Database Connection

Two Files involved:
index.php (html markup, db connection and class object)
getajax.php (db connection, sql + response code)
Need to see how can I eliminate the duplicate connection details off the getajax file and reuse the existing class connection function or contruct on index.
Already using mysql_pconnect for connection reuse on the getajax file and index.
Should I create an extended class for "getajax" so it extends primary object?
Trying to avoid overkill on DB when lots of calls are made to sql.
Simply using pconnect is sufficient. As noted in the PHP documentation about persistent database connections:
they do not give you an ability to
open 'user sessions' on the same link
That is, simply using pconnect tells PHP to use an existing connection if it's available. Whether or not it was the same connection used by the first PHP call is unimportant.
Make sure you read that PHP manual page - there are some important caveats.

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