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.
Related
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
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
I'm trying to connect to my SQL database and I'm getting the error mentioned above.
This is the PHP code
// This file has database info variables (password etc.)
include "db_config.php";
class DB_CONNECT
{
function __construct()
{
$this->connect();
}
function __destruct(){}
function connect()
{
$connect = mysql_connect($db_server, $db_user, $db_password) or die();
$db = mysql_select_db($db_name) or die();
echo "Connection successful!";
return $connect;
}
}
// Just to try out if the connection is successful
new DB_CONNECT();
This is the error
Warning: mysql_connect(): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /hermes/bosnaweb05a/b1/ipg.matejhacincom1/dbtest/db_connect.php on line 16
The funny thing is that I can connect to the database easily with this code which is generated for db testing by my hosting provider:
$link = mysql_connect('my db server', 'db user', 'db pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(my db table);
Could someone let me know what I'm doing wrong? I have no idea anymore.
The reason I mentioned that I'm not the server adming is because I saw a lot of questions like this here, but all of them have instructions how to solve it by using some server commands etc.
Either:
There isn't a MySQL server running on the same machine as the webserver or
The MySQL server is configured to place its socket file somewhere other than /var/run/mysqld/mysqld.sock (in which case you need to specify where it is or
The MySQL server is configured to listen only on TCP/IP (which is inefficient but it can be accessed by using the 127.0.0.1 IP address instead of localhost).
Probably in variables $db_server, $db_user, $db_password you have wrong data. You must pass to object data from db_config.php file. For example through constructor.
Have the same problem on an customer server, last week, then :
Be sure your $db_server is according your hosting ; not a remote server.
Then use 127.0.0.1 instead of localhost
In my case, the MySQL server was different the PHP.
Thank you for all of your answers but what solved my problem was nothing that was in any of your answers.
All I did was used PDO instead of deprecated mysql and it worked. I also for some reason needed to move inclulde "db_config.php" in to the class because variables didn't work otherwise.
Anyway, here's the code that now works:
class DB_CONNECT
{
function __construct()
{
$this->connect();
}
function __destruct(){}
function connect()
{
include "db_config.php";
$connect = new PDO($db_server, $db_user, $db_password) or die();
echo "Connection successful!";
return $connect;
}
}
// Just to try out if the connection is successful
new DB_CONNECT();
I have this index.php :
<?php
require_once ('required1.php');
require_once ('required2.php');
--- some mysqli_query here ---
?>
what's inside that required1.php is this :
<?php
$DbServer = 'localhost';
$DbUser = 'username';
$DbPassword = 'password';
$DbName = 'dbname';
$con = mysqli_connect($DbServer, $DbUser, $DbPassword, $DbName);
?>
and this is required2.php :
<?php
require_once 'required1.php';
--- some mysqli_query here ---
mysqli_close($con);
?>
the mysqli_close($con); on required2.php makes mysqli_query on index.php failed because the mysql connection already closed by required2.php.
how to make required2.php works independently? I mean, what ever happen on that file (required2.php) leave it there. don't bring anything into other file who calls it, specially the mysqli_close($con);
is it possible with require_once? or PHP have another function to make it like that? thanks!
Use a different connection in require2.php or don't close it. You can also include it at the bottom.
Using mysqli_close($con); in required2.php closes the connection, so after any include of required2.php, $con won't be available.
If you want required2.php to be independent, you have to use another database connection, not $con.
First of all, there is really no need to close the connection in your included file (there may be very specific exceptions...).
If you want to use your second include independently, you should refactor it to OOP. If it is a class that gets its database connection injected via its constructor (dependency injection), it would only show its name to the rest of your code so things that happen in the class or an object, would not affect the rest of your code.
Of course you still should not close your connection as that object will likely be passed around by reference but using objects / classes instead of procedural code will make it more independent an reusable.
if required2.php has nothing to do with your current script, but all you need to do is to run the script as you mentioned, i feel you can call the file required2.php using file(). this will run both the scripts separately and even if you close connection in required2.php it does not effect the current script.
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.