mysqli - Do I really need to do $result->close(); & $mysqli->close();? - php

Just started using mysqli. If I'm working with small data sets on small websites (traffic-wise), do I really need to use these all the time?
$result->close();
$mysqli->close();
Also, for someone doing custom PHP and MySQL work without a framework, is mysqli the general preferred way of interacting with MySQL?

PHP will close all open files and DB connections at the end of the script. It's good practice to do it manually when you are done with the connections, but it's no disaster if you don't. If you have a DB connection that will be used throughout the whole script you can as well leave it open.
+1 on PDO

According to current documentation, you should always use $mysql->kill() in addition to $mysql->close().
$thread = $mysqli->thread_id;
$mysqli->kill($thread);
$mysqli->close();

You should get in the habit of doing cleanup right (calling close as soon as you're done), or the resource leaks can gradually accumulate until they impact performance.
As far as what DB layer, learning PDO should be worthwhile because it is well-designed and compatible with all the major databases.

It is a good practice to release resource early when it is no more needed, this may avoid resource peek out when there are more number of concurrent user accessing the same page

Related

The most efficient way to use mysqli connection

I am searching for a efficient way to use PHP MySQL innoDB connection but not able to found conclusive information on the web.
As I know, persistent connection is much faster than non-persistent one,
we can set up the connection in following way:
$instance_mysqli = new mysqli('p:127.0.0.1', 'username', 'password', 'db');
However, from the official website, it said the default behavior is "reset" on reuse, which is slower. http://php.net/manual/en/mysqli.persistconns.php
The mysqli extension does this cleanup by automatically calling the
C-API function mysql_change_user(). The automatic cleanup feature has
advantages and disadvantages though. The advantage is that the
programmer no longer needs to worry about adding cleanup code, as it
is called automatically. However, the disadvantage is that the code
could potentially be a little slower, as the code to perform the
cleanup needs to run each time a connection is returned from the
connection pool.
So, there is no way to pass parameter to the above constructor to avoid "reset"? The only way is to recompile extension from source code as the document suggested?
And my anther question is... if mysqli is so smart that it can automatically reset connection by default, what is the point many people still use non-persistent connection, which is even slower.
The cost of a connection is quite small, whether it is persistent or not, whether there is cleanup or not.
Normally, one should acquire one connection at the beginning of the program, and keep it until the end. (There are some exceptions.)
The only time a connection is really noticeable is if you acquire a connection before each and every SQL query.
Bottom line: Worry about your indexes, system design, etc, not about acquiring the connection.

Is it safe to use persistent connection using PHP mysqli interface?

There are quite a few blog/links which discourage usage of persistent connections, mainly because the cleanup needs to be done on client side, and cases where transactions/locks have to be correctly rolled back. However, those links are old, and not enirely in context of mysqli PHP interface.
I read the link : The mysqli Extension and Persistent Connections
It clearly suggests that it does most of the desired cleanup when a client terminates unexpectedly:
Rollback active transactions
Close and drop temporary tables
Unlock tables
Reset session variables
Close prepared statements (always happens with PHP)
Close handler
Release locks acquired with GET_LOCK()
Now that pretty much does most of the cleanup, including READ/WRITE locks on tables if any acquired. So I believe it should be safe. Can I be wrong?
Also, it says there are some performance penalty in form of extra time needed to do cleanup. I would like to know how much that may be in terms of millisecs? Can it ever be as large as say 100 ms?
The automatic cleanup feature has advantages and disadvantages though.
The advantage is that the programmer no longer needs to worry about
adding cleanup code, as it is called automatically. However, the
disadvantage is that the code could potentially be a little slower, as
the code to perform the cleanup needs to run each time a connection is
returned from the connection pool.
I wonder if you really think you can trust an answer from anonymous passer-by more than official documentation page, that clearly answers your question.
But if you do - yes, you can believe it should be safe.
As of performance penalty, from the way it is asked, I believe you don't really need persistent connections at all.

avoid connection overhead to database in php

how can the session be handled in php for database connection so as to avoid the overhead of connecting every time to the database?
Note:connection to the database is through odbc.
Have a look at persistent connections (example #4) at the PHP docu.
Maintain thr database object from your very first query. Some people use $_GLOBAL but that has a few implications certain developers arnt comfortable with. Personally I use it because it's the simplest approach.

What are the implications of opening MySQL connections over and over again in PHP

Specifically, I have a DB class that opens and closes multiple MySQL connections every time I call the Query function in the class. Should I open a connection once? or is it ok to open and close connections like this?
My simple-minded (ISAM, no transactions) C-language app runs for eight hours a day, updating multiple tables in one database over one single MySQL connection that stays open the whole time. It works just fine. Anytime there's any kind of MySQL error (not only server gone away), the code just calls mysql_real_connect() again and it picks right up without any trouble. Reconnection is one of the places where, in my opinion, MySQL functions flawlessly.
But there's plenty of controversy and discussion about the goodness/badness of persistent connections. You can find some of it here:
http://www.google.com/webhp?hl=&sourceid=navclient-ff&rlz=1B3GGLL_enUS384US384&ie=UTF-8#rlz=1B3GGLL_enUS384US384&hl=en&source=hp&q=mysql+persistent+connection&aq=0&aqi=g4g-m5&aql=&oq=mysql+persistent+conn&gs_rfai=Ch2c6iCchTO3zG4i6MZ-i7JAOAAAAqgQFT9BAKCs&fp=ff274912d96214e6
-- HTH
If you don't want to change much instead of mysql_connect() use mysql_pconnect()
This way you will use the opened connection. Bu I would agree with #Sarfraz Ahmed - use it only once
Should I open a connection once?
No.
I thought it would be better to release the memory
Actually, connect itself do not consume memory.
And - most important part - you should not worry of such imaginable things.
Don't make decisions on based on empty assumptions.
Here is 2 simple rules to follow:
When you don't know, what to do, do it most general way, as everyone does.
Do necessary things only. Don't try to foresee every problem in the future. Deal only with present problems, not with imaginable ones. Premature optimization is the root of all evil, as it said.
Should I open a connection once? or is
it ok to open and close connections
like this?
You should open multiple connection only when needed otherwise it is not a good idea to open multiple connections thereby consuming a lot of memory which is an overhead.
In general, go back to the simplest MySQL tutorial you can find and do it just that way. Don't deviate unless you have a problem you are trying to solve.
MySQL works just fine when you keep it brain-dead simple. Don't add complexity.
BTW, are you writing yet another MySQL abstraction layer? Why? This question is a good example why reinventing a wheel can be risky.
conecting also uses cpu time. so if you reconnect about 8 times per page, and you have somewhat about 100 visitors a day wich call up 5 pages in average you have 8*100*5=4000 reconnects in one day. and thats a small website. you should realy think about connecting only once or when the connection is getting lost. that would somehow lower your electricity bill also ;-)
I think you should use a Registry Object to open your Database Connection, and make your Database Object a singleton.
Registry::Set('DB', new Database());
$DB = Registry::Get('DB');

Why specify an explicit database connection?

I am making a simple blog for myself and while reading through the PHP manual, I found this http://us2.php.net/manual/en/function.pg-query.php
It says
resource pg_query ([ resource
$connection ], string $query )
...
Note: Although connection can be omitted, it is not recommended, since
it can be the cause of hard to find
bugs in scripts.
Why is it not ok to just use the last connection? I never plan on having more than 1 connection open per PHP script, so how would this ever cause bugs for me?
Hah. "I never plan on having more than 1 connection open per PHP script."
I remember the last time I said that. It was back in 'ought three. I was a young whippersnapper then, much like yourself. Full of spit and vinegar. Why do something if I don't have to? That was the prevailing wisdom in our little dot-com startup. "Just get it done!" we'd shout. Also, we wore onions on our belts.
Well... time came that I added a quick little statistics database in to the main site. Nothing special, just wanted some stats tracked separately. I figured I'd re-use the database wrapper. It was a good wrapper for it's time! Abstracted out all the database functions I'd need. But as soon as I added it in there, some wacky things started happening. It didn't make sense. I had two separate database wrapper objects... two separate connections! How could they affect each other? But then users would be logged out randomly. Sessions would fail. Sometimes a key update would go bad. Some queries ran on the wrong databases. Dogs and cats started living together! It was mass hysteria!
If only I had specified that connector originally. If only I had kept them specific, so pg_query would know which one to use. So much data loss could have been prevented. So many good tuples... so much good data. Lost. Lost...
*sniff *
This is to accommodate those who need explicit calls to various databases. If you don't, ignore it :) Some scripts work on local and remote databases, and yet others work on multiple local or multiple remote databases.
Perhaps it is due to the order of arguments? If it was regarding a recommendation to explicitly use a connection resource, the same note would be on mysql_query(). Unless there is something specific to PostgreSQL I am unaware of.
In short, I don't see any problem omitting the connection argument for single connection applications.

Categories