Check MySQL connection - php

I am a paranoid kind of guy and even though I included mysql_close() in my PHP functions after I do something, is there a way I can check (besides another query) to see if the connection is still open, just for assurance.

The mysql_close() function returns true if it succeeded. By adding an extra check outside of checking the return value of mysql_close(), you aren't doing anything helpful, and adding another place bugs can crop up in your code.
In any case, non-persistent connections are closed automatically when your script finishes, so it isn't necessary, unless you have some specific reason to kill off the resource ahead of time.

You may want to try mysql_ping()
Here is an excerpt from that page:
bool mysql_ping ([ resource $link_identifier ] )
Checks whether or not the connection to the server is working.
If it has gone down, an automatic reconnection is attempted.
This function can be used by scripts that remain idle for a long while,
to check whether or not the server has closed the connection and
reconnect if necessary.
Note: Since MySQL 5.0.13, automatic reconnection feature is disabled.
As for this excerpt, I do not know whether the automatic reconnection feature is disabled comment refers to mysql or PHP. You will have to experiment with it to find out. If this reconnection issue is indeed true, then #Brad's answer is paranoid-proof since you could run mysql_close immediately after querying the data and fetching it. You can be sure at that point that there is no valid connection since you explicitly closed it. Consequently, you would have to run mysql_connect for your next query.
However, letting non-persistent connections close on there own is not always a good idea because this could potentially stockpile TIME_WAITs in the DB Server's netstat. This would fool webservers into thinking that DB Connections are no longer available because MySQL ran out where the OS would actually be the cause since it would delay releasing Connection Resources. To be better safe that sorry, run mysql_close when done and mysql_connect/mysql_query for the next query.
If you are willing, you could construct a try-catch paradigm or a set of if-then-else stataments to first run mysql_ping on an established connection. If true, use it with mysql_query. Otherwise, run mysql_close/mysql_connect/mysql_query.

$con = mysql_connect("localhost" ,"name", "pass");
/* your code*/
if ($con){
mysql_close();
}

AFAIK if you open mysql connection with mysql_pconnect(), they don't really clossed after mysql_close(), it's just return to connection pool

Related

Does PHP exit() also close open result sets?

I like to close SQL result sets after I'm done using them with either sqlsrv_cancel($result) or mysqli_free_result($result) depending on the type of connection I'm using.
If I need to call exit() before I call either sqlsrv_cancel or mysqli_free_result is $result implicitly cleared from memory?
By the looks of it: yes.
Open non-persistent MySQL connections and result sets are automatically destroyed when a PHP script finishes its execution.
http://php.net/manual/en/mysqli.close.php
Calling exit() or die() stops PHP script execution.
Yes, it does close the connection and clears from memory, except if you've got a persistent database connection.
Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
You can read more about it at http://php.net/manual/en/features.persistent-connections.php
You should close the connection because it takes a few seconds or even minutes to close the connection automatically. So, if you have a lots of traffic, you should close the connection as fast as you can so other traffic can use it.

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.

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.

how to solve Too many connections in mysql error?

I have a php application. There is a lot of database operation and i do mysql_connect() to open connection. Do I have to close the connection manually?
In general, after script execution the connections should close automatically. However in some cases (e.g. like yours) you have no other way but to do it manually (make mysql_close($connection) to be the last line of your script).
Alternatively, consider using mysql_pconnect() to have persistent connection, which doesn't close after script completion, and is (implicitly) reused on the next request.
Yes. But you do mysql_connect() many times. you can keep it in seperate file and include where ever needed.
Increase the number of allowable connection in mysql settings should do the trick i guess. But before that make sure on each page you are only opening the mysql connection once. At the end of the script the connection should automatically be closed, so no you dont really have to close it manually.
Use singleton to keep just one open connection on each page.

PHP and MySQLi close()

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?
Is it necessary?
What exactly does it do?
I heard that after PHP runs its script that it closes the
connection, is that true?
Lastly, is there a security issue when not closing your connection
to the database?
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.
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

Categories