2

I need to save the value of mysql_connect() in a global variable that's accessible in every php file in my project for example, $db_ServerVal = mysql_connect().

I need to be able to call mysql_connect only once, at the start of the program.

Then in every php file -- that $db_ServerVal MUST be valid. Not the first time. EVERY time. Until I call mysql_close( $db_ServerVal);

Can I use $GLOBALS[], the pre-defined array in php, to store my $db_ServerVal database connection?

The other problem is -- I need have a 'close' event when the browser window closes, so that I will know that it's time to call mysql_close( $db_ServerVal);.

I can't call mysql_close() at the end of my index.php file since that will close the database prematurely, then every time I access the database I'd have to mysql_connect() again.

While I could call mysql_connect() and mysql_close() before and after each database call -- I'm not sure if that's the standard way things are done.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
wantTheBest
  • 1,682
  • 4
  • 43
  • 69
  • 1
    why dont you have a class that handle all your database interactions – Ibu Jun 10 '11 at 21:43
  • How about using [$_SESSION](http://www.php.net/manual/en/book.session.php) and MySQL? [This class](http://www.php.net/manual/en/book.session.php#100180) could be useful. – quantme Jun 10 '11 at 21:44
  • @quantme, I'm new and didn't know about $_SESSION -- is it better than using $GLOBALS to store an open database connection? – wantTheBest Jun 10 '11 at 21:45
  • @Ibu -- I'm getting to OO later, but yep that's what I'll end up doing. Just trying to learn first things first, I am a noob with php and mysql. – wantTheBest Jun 10 '11 at 21:46
  • I don't know too much about $GLOBALS except that the use of $_SESSION is safer; at least in my experience. If you want to receive more help from the community edit your question using the code you're working with. – quantme Jun 10 '11 at 21:51

5 Answers5

2

first, you do not need to store this variable, as ALL of the mysql_* function will use the last opened connection if you omit the db_connection argument. you would only need to store this if you were to open multiple db connections at the same time.

second, the mysql connection will automatically close at the end of your script. there is no need to close it in most cases.

third, you shouldn't use mysql_* anymore. either use mysqli_* or the recommended PDO class.

dqhendricks
  • 19,030
  • 11
  • 50
  • 83
  • Sometimes you need the link_id stored in a variable if you want to use the string escape functions in php – Brian Patterson Jun 10 '11 at 21:48
  • 1
    @Brian Patterson you are wrong. mysql_real_escape_string() does NOT require a connection resource. this is an optional argument. if the argument is ommited, the last opened mysql connection is used. – dqhendricks Jun 10 '11 at 21:50
  • +1'ed -> This. Is. It. Also, _please please please_ avoid using global namespace for variables. It is a ___very bad___ programming practice. – Stephane Gosselin Jun 10 '11 at 21:55
2

Don't close the database each time. You could even choose not to close the connection at all, since it will implicitly be closed at the end of script.

If you want to be able to connect at all times, you could write a function for that:

$_connection = false;
function getConnection()
{
  global $_connection;
  if (!$_connection)
    $_connection = mysql_connect( ... );
  return $_connection;
}

function closeConnection()
{
  global $_connection;
  if ($_connection)
    mysql_close($_connection);
  $_connection = false;
}

Of course, embedding the connection in an actual class is even better, but this will get you started to fix you problem. Baby steps. :)

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
1

This is from my db class, but I think this should help you. Just open the first time you need it and close at the end of your page. Or, like I do , have the connect in the contructor of your db class, and the close in the destructor.

//Constructor Code
$this->link_id = mysql_connect($this->db_host, $this->db_user, $this->db_pass);


//Destructor Code
@mysql_close($this->link_id);

Here is a sample of the 2 methods i use.

    //forward php4 to constructor
    function db_class() {

        return $this->__construct();
    }

    //constructor
    function __construct() {

        register_shutdown_function(array(&$this, "__destruct"));

        $this->link_id = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
        mysql_select_db($this->db_name, $this->link_id);

}
    //destructor
    function __destruct() {


        @mysql_close($this->link_id);

    }
Brian Patterson
  • 1,615
  • 2
  • 15
  • 31
1

I typically do my database connection call on a per page basis, not per query basis. So I include the file that does my database connection at the top of each file in which I need to connect:

require('db_connect.php');

And close it after I've done anything on the page that needed the connection. What you should do is based on your needs, however, so in that sense, it depends.

kinakuta
  • 9,029
  • 1
  • 39
  • 48
  • Thanks dude, I'm going to do the per-page connection as you suggest. At the bottom of my index.php in the sample php/mysql code I got from a book was a call to mysql_close( $db_ServerVal). I finally realized reading all the comments that index.php displays my form then goes out of scope -- ie. the mysql_close() is called, yet my form is still visible. When I click 'submit' on the form and re-enter the code -- index.php is LONG gone and the $db_ServerVal is null. That took me 5 hours. Pretty humbling, folks. I'm reading all your comments and I like them all, thank you, I'm learning a lot. – wantTheBest Jun 10 '11 at 22:20
  • This is much better than using globals. I could still add a couple of details though. For one, parentheses are not needed for require and include calls as they are language constructs. Also, require_once would be a bit better because if you ever have a script in a script that both call require, this will be a show stopper. So then the line above now becomes `require_once 'dbconnect.php';` Last detail, if you don't want the script to do hard die if connection is not available -> to give user error message for example, better use include. require throws a fatal error, include throws a warning. – Stephane Gosselin Jun 11 '11 at 06:21
1

You can store the connection object in a global variable and access it via $GLOBALS. Note that unless you are using persistent connections (and you should know what you are doing if you do), the database connection will automatically close when your PHP script ends anyway.

ldg
  • 9,112
  • 2
  • 29
  • 44
  • ALthough you _do answer the op's question_, using globals is not the way he should be learning to implement in his scripts. – Stephane Gosselin Jun 10 '11 at 21:52
  • @stef Hey, I very much suspect you're trying to help -- I'd only point out that I'm new here. Think of a new guy on the team and we're trying to help him out -- I'm that new guy. To the point, you failed to read what I said earlier -- I'm learning this at my pace, not yours, I know about evil global variables, I'm 51 years old and was writing code in the 1970s. So give it a rest, youngster! Thanks in advance for your patience, as it's clear from your profile how knowledgeable you are. – wantTheBest Jun 10 '11 at 21:59
  • @wantTheBest - I am hitting 44 soon, not too far from your 51. Being called 'youngster' sure felt good though! As for using globals, yes I was only trying to help. There is always an alternative to using a global variable, if you _really_ need a global, it is in my opinion always well worth changing the design to avoid this need. And hey! I wish you a warm welcome on the SO community, this is just me ranting and giving my _stronly opiniated_ 2 cents on the matter. The advice I put out is just that: advice. You do what you want with it friend! ;o) – Stephane Gosselin Jun 10 '11 at 22:26
  • @wantTheBest -> Came back to [post this just for you buddy](http://blog.case.edu/gps10/2006/07/22/why_global_variables_in_php_is_bad_programming_practice), old but ever so relevant. – Stephane Gosselin Jun 10 '11 at 22:31
  • @stef I'm so used to writing non-web apps, the persistance of objects only ends when a destructor is invoked for an in-method object instance, but at header file scope, an instance stays alive until the .EXE is closed by the user. What I lacked was the perspective of web pages and server-side script coming into scope then going out of scope quickly. So I'll think about each page, each .php file, etc. as an .EXE that executes and terminates quickly then destructs everything and closes all db connections, so if a repost occurs, any needed objects (like db connections) must be re-instantiated. – wantTheBest Jun 10 '11 at 23:38
  • @wantTheBest yes sir, that's a pretty good way to see it, the .EXE in scripting _has a very short 'lifespan'_. You will soon be yearning for persistance though. We all do at some point! At this point, please go dive into [this section of the manual](http://php.net/manual/en/features.sessions.php) and you will happily be able to avoid passing variables between pages and other such nonsensical hacks I went through to fulfill this need when I started scripting. Wish I had SO back then , it would of saved me a couple of years worth of bad habits. Happy coding my friend, see you around. – Stephane Gosselin Jun 11 '11 at 07:29