2

I have following in my config.php file for one of my web app.

//db settings
    $host = 'localhost'; //database location
    $user = 'example'; //database username
    $pass = 'example12'; //database password
    $db_name = 'example'; //database name

//create db connection
    $link = mysql_connect($host, $user, $pass);
    mysql_select_db($db_name);

//sets encoding to utf8
    mysql_query("SET NAMES utf8");

I am including config.php in all pages of my application at top (1st line of code).

I want to know that will PHP/MYSQL maintain connection open and close automatically or I need to explicitly call them. Connection is opening by itself, as I am doing all db based tasks properly. But not closing connection anywhere, this is a high traffic website.

Please correct me if I am wrong anywhere.

Thanks!

djmzfKnm
  • 26,679
  • 70
  • 166
  • 227

1 Answers1

6

The connection will close automatically upon termination of the script.

The notes on mysql_connect() state that:

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().

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
  • 1
    You should close it explicitly when you're done with it, though, unless it's as near as makes no difference. – Lightness Races in Orbit Feb 09 '11 at 09:49
  • I suppose your comment is targeted at me, @MohammadSaberi? The actual PHP script's execution is referred to here. Not the execution of a single query. You'd have to `mysql_connect()` after each query if this'd be the case. – Linus Kleen Apr 17 '12 at 13:53
  • @LinusKleen, you are right and I was wrong. I mean will closing mysql connection occur after each operation on mysql, or after executing and loading the whole of our web page ? – Mohammad Saberi Apr 17 '12 at 16:08