When do I have to close mysqli (Database) connection? - php

For now, I have one connect.php file e.g.
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
$con = new mysqli(
$mysql_host,
$mysql_user,
$mysql_password,
$mysql_database
);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
In every other PHP file that uses MySQL queries, I use "include 'connect.php';"
For Instance on W3Schools, they create for every query a new connection and then close it after use. See here: w3schools.com: I'm not sure if they do it just for showing purpose, or if it is best practice to do it this way.
Do I have to close the connection after each selection and then establish a new one, for the next query? If not, when do I finally have to close the connection? On the end of the PHP File with all the queries?

A quote from the php.net site.
Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. 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.
Source: http://php.net/manual/en/mysqli.close.php

Close the connection when you are done using it for that page. If you have, say, a blog, the button that you use to post it would start the code that would open the connection, do some work with the connection (like adding it to your db and or showing it on a page) and then it would close the connection so that it isn't open any longer than it needs. But when you click the button again it would start the process over, only using resources as it needs them.

Best practice is to use close function in footer.php

Related

PHP Warning: mysqli_connect(): (HY000/1040): Too many connections [duplicate]

For now, I have one connect.php file e.g.
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
$con = new mysqli(
$mysql_host,
$mysql_user,
$mysql_password,
$mysql_database
);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
In every other PHP file that uses MySQL queries, I use "include 'connect.php';"
For Instance on W3Schools, they create for every query a new connection and then close it after use. See here: w3schools.com: I'm not sure if they do it just for showing purpose, or if it is best practice to do it this way.
Do I have to close the connection after each selection and then establish a new one, for the next query? If not, when do I finally have to close the connection? On the end of the PHP File with all the queries?
A quote from the php.net site.
Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. 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.
Source: http://php.net/manual/en/mysqli.close.php
Close the connection when you are done using it for that page. If you have, say, a blog, the button that you use to post it would start the code that would open the connection, do some work with the connection (like adding it to your db and or showing it on a page) and then it would close the connection so that it isn't open any longer than it needs. But when you click the button again it would start the process over, only using resources as it needs them.
Best practice is to use close function in footer.php

PHP - Best way to connect to database when there are multiple connections

I have just recently acquired the service side of a medium size project. The former developer has all of his functions as separate php scripts instead of classes (func1.php, func2.php, etc)... All these 'functions' make a reference to mysqli_connect via referencing the actual
'databaseonnection.php' file. This is creating a new connection every time any of the scripts run (every time I have to call a function) and I don't want to do that. I was thinking about having a persistent connection, but I'm worried about it getting out of hands as the project is growing more and more every day. So, has anyone ever encountered a similar situation? What is the best way to handle my connection to the database? Any suggestions would be greatly appreciated.
From the docs for mysql_connect. 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.
EDIT: I'm sorry I thought you wanted connectivity help. There is no way except to move all those "functions" into one file where the connection is for them only.
I create a con.php file where my PDO connection is established then include that file anywhere you wish to use a connection Here is the base for a PDO connection:
$PDO = new PDO("mysql:host=localhost;dbname=dbname", "user_name", "password");
Here is my notes on using the PDO object to make prepared queries. There is more than you need below but good luck.
Within your PHP file that needs a connection:
1: include('con.php');
2: $datas = $PDO->prepare(SELECT * FROM table WHERE title LIKE :searchquery);
// prepare method creates and returns a PDOstatment object ( print_r($datas); ) which contains an execute() method
// PDOstatment object has its own methods ie. rowCount()
// $datas->bindValue(':search', '% . $search . %', )
// Optional - Manually bind value. see http://php.net/manual/en/pdostatement.bindparam.php
3: $datas->execute( array(':searchquery' => $searchquery . '%'));
// pass in values that need to be bound AND EXECUTE.
// There are 17 ways to "fetch" data with the PDO object.
4: $datas-fetchALL(PDO::FETCH_OBJ);
close a pdo connection by the handle:
$PDO = null;
I think you'll be much better off using PDO as opposed to the old MYSQL functions e.g. mysql_connect. It's much more robust an interface.
Below is the basic code to do this:
$db_handle = new PDO("mysql:host=".$db_host.";dbname=".$db_name.";port=".$db_port."", $db_username, $db_password, $connect_options);
where $db_handle is the PDO object representing the database connection, $db_host is your hostname [usually localhost], $db_name is the name of your database, $db_port is the database port number [usually 3306], $db_username and $db_password are your database user access credentials, and $connect_options are optional driver-specific connection options.
To enable persistent connections you need to set the driver-specific connection option for it before opening the connection: $connect_options = array(PDO::ATTR_PERSISTENT => true); then execute the earlier database connection code.
You can get more information on this from the PHP Docs here: http://www.php.net/manual/en/pdo.construct.php and http://php.net/manual/en/pdo.connections.php.
Regarding creating persistent connections, I would suggest that you close every database connection you open at the end of your script (after all your database operations of course) by nullifying your database handle: $db_handle = NULL;. You should do this whether you opened a persistent connection or not. It sounds counter-intuitive, but I believe you should free up any database resources when your script is done.
The performance disadvantages of doing this [from my experience] are neglible for most applications. This is obviously an arguable assertion and you may also find the following link helpful in further clarifying your strategy in this regard:
Persistent DB Connections - Yea or Nay?
Happy coding!
if you have very complex project and need big budget to re-design, and prefer very simple alteration then
1) stay in mysqli_connect
2) move the database connection to header of your script.
3) remove the function databse close() on that functions.
4) remove the connection link variables, it wont needed for single database.
5) close the database on end of footer.
By this way, database connection establish when starting your script and after all queries, it will be closed on footer. your server can handle the connections without closing/re-open by using keepalive method. basically default keepalive value is 30 to 90 seconds.

mysql_close(): 5 is not a valid MySQL-Link resource in C:\wamp\www\Includes\footer.php on line 4

Everyth worked fine, it just decided to stop working and it ruined my whole project and Im at standstill.
This is error:
mysql_close(): 5 is not a valid MySQL-Link resource in
C:\wamp\www\Includes\footer.php on line 4
This is footer.php
<?php
//close connection
if (isset($dbh)); {
mysql_close($dbh);
}
?>
This is connect.php
//set constants
require("quick.php");
//database connection
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if (!$dbh) { //check connection
die("Cannot conect! to database ");
}
//selecting database
$db_select = mysql_select_db(DB_NAME, $dbh);
if (!$db_select) { //check connection
die("Cannot connect to database ");
}
?>
Basically whenever I try to quit mysql this error shows.
And it all worked fine not long ago.
Try this instead:
if (isset($dbh) && is_resource($dbh)) {
mysql_close($dbh);
} else {
mysql_close();
}
From manual:
mysql_close() closes the non-persistent connection to the MySQL server
that's associated with the specified link identifier. If
link_identifier isn't specified, the last opened link is used.
Maybe he's having few connections.. Who knows..
Somewhere, within your page, there is an assignment that puts $dbh = 5; that overrides your database connection. That is the cause for the error. Search for any assignments to that variable between your database opening and your footer, and you've found your problem.
Note: I wouldn't be that worried about the connection being open as some other commenters here, since if it's not a persistant connection, it will anyway be closed at the end of the script, so I don't see how that would be ruining your whole project. Your code tries to close it at the footer which is not much different than letting it close itself. From the manual:
Using mysql_close() isn't usually necessary, as non-persistent open
links are automatically closed at the end of the script's execution.
See also freeing resources.
All the mysql_* functions will assume "the last connection you opened" if you don't specify a connection. This is useful because you don't have to keep track of it like you do for other libraries. Most likely here you are overwriting the variable $dbh somewhere. Personally I'd use a variable like $_connection if I use one at all.
So just mysql_close() will be enough to close the connection. You need only worry about this kind of thing if you are handling more than one connection at a time.

Do I need to use mysql_close(connection)?

I have the following code in db.php to connect to my DB.
<?php
$DB_HOST = "localhost";
$DB_NAME = "db";
$DB_USER = "user";
$DB_PASSWORD = "pass";
$con = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($DB_NAME , $con);
?>
In my other script I include it using:
include("db.php");
In some cases I receive the ff error:
[10-Mar-2012 10:47:20] PHP Warning: mysql_connect() [function.mysql-connect]: User db_user already has more than 'max_user_connections' active connections in /home/user/public_html/sc/db.php on line 8
Now, I am wondering if I need to close the connection like:
<?php
include("db.php");
//other stuff here
mysql_close($con);
?>
BTW, I have a value of 100 max_connections in my MySQL config.
I also research about persistent connection and I believe my code above is not a persistent connection.
No, this won't help you if you close it at the end of the script. mysql_close() is just useful in case you want to free up resources before you end your script, because your connection is closed as soon as execution of the script ends
If you don't close your connections, they will stay open and take up precious resources on the server. I guess there's there the security point too, you don't want to risk someone getting a hold of the connection.
I prefer to put my database in a class and use __construct to create the connection, and __destruct to close the connection. If your unfamiliar with classes. The __construct and __destruct gets called automatically when you create and destroy a class.
Edit:
There was originally meant to be an example. But I have a basic but working mysql class here https://stackoverflow.com/a/9651249/1246494.
It shows the usage of mysql_close and how I was trying to relate it to the class destructor. The point was, any network connection should be closed, whether your database is on a remote server, or localhost.

Do SQL connections opened with PDO in PHP have to be closed

When I open a MySQL connection in PHP with just PHP's built-in MySQL functions, I do the following:
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
//queries etcetera
mysql_close($link);
When I open a connection with PDO, it looks like this:
$link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password);
//prepare statements, perform queries
Do I have to explicitly close the connection like I do with mysql_connect() and mysql_close()? If not, how does PHP know when I'm done with my connection?
TIA.
Use $link = null to let PDO know it can close the connection.
PHP: PDO Connections & Connection Management
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.
PDO does not offer such a function on its own. Connections via PDO are indirectly managed via the PDO objects refcount in PHP.
But sometimes you want to close the connection anyway, regardless of the refcount. Either because you can not control it, need it for testing purposes or similar.
You can close the Mysql connection with PDO by running a SQL query. Every user that is able to connect to the Mysql server is able to KILL at least its own thread:
/*
* Close Mysql Connection (PDO)
*/
$pdo_mysql_close = function (PDO $connection) {
$query = 'SHOW PROCESSLIST -- ' . uniqid('pdo_mysql_close ', 1);
$list = $connection->query($query)->fetchAll(PDO::FETCH_ASSOC);
foreach ($list as $thread) {
if ($thread['Info'] === $query) {
return $connection->query('KILL ' . $thread['Id']);
}
}
return false;
};
$pdo_mysql_close($conn);
Related Mysql Documentation:
13.7.5.30. SHOW PROCESSLIST Syntax
13.7.6.4. KILL Syntax
Related Stackoverflow Questions:
PHP PDO close()? (Apr 2012)
When the PHP script finishes executing, all connections are closed. Also you don't have to explicitly close your connection with mysql_close().
You can also limit your connections to within local functions. That way the connection is closed as soon as the function is completed.
Well seeing as the $link for the PDO is assigned an object, PHP would set that as null as soon as the script runs so that it's no longer an object. Therefore you could just do:
$link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password);
//prepare statements, perform queries
$link = null;
http://uk3.php.net/pdo
From what i gather i could not see anyway to close it in the php manual, and examples of scripts i quickly looked at never closed the connection in anyway from what i could see.

Categories