Here's how I do it using functional PHP programming (you may prefer using OO
PHP which I don't bother with) :

I include a generic functions file in each page. You could take it further,
opening and closing the database connection for every query, but this way is
more efficient if more than open query is run against the database on each

create "functions.php" which contains the following:



function open_db()
  global $link;
  $link = mysql_connect("localhost", "user_name", "password") or die("Could
not connect");
  mysql_select_db("database_name") or die("<p>Could not select

function do_query($query)
  global $result;
  $result = mysql_query($query)
      or die("<p>Query failed.</p>"
            ."<p>MySQL said ".mysql_error()."</p>"

function close_db()
  global $result;
  global $link;
  /* Free resultset */
  /* Closing connection */


Then use "functions.php" in each web page you code


do_query("SELECT name FROM FISH; ");
$num_rows = mysql_num_rows($result);
if( $num_rows == 0 ) {
    // handle no rows returned here
while ( $row = mysql_fetch_array($result) ) {
    // do stuff here......... like using $row["name"];

// run more queries if you like here


----- Original Message -----
From: "Morten Twellmann" <[EMAIL PROTECTED]>
Sent: Sunday, July 27, 2003 1:01 PM
Subject: [PHP-DB] MySQL Session

> I have just recently entered the world of PHP and MySQL. I'm used to code
> ASP with Access databases and since I am not very familiar with PHP, I
> run into a problem, which is probably quite easy to solve:
> Connecting to the database requires a couple lines of code, which I would
> rather not have to write on every single page, which needs the database
> connection.
> ($link = mysql_connect("host", "username", "password")
>    or die("Could not connect : " . mysql_error());
>   mysql_select_db("dbname") or die("Could not select database.");)
> In ASP this is easy to solve, since I would just create a "global.asa" and
> on the Application_OnStart procedure, I would create the global database
> connection and then reference to that variable on each of the individual
> pages.
> Now, in PHP I do not seem to be able to create a "global.asa" or anything
> similar. It does not even seem to have an "Application" object, which I
> refer to on any page.
> Can anyone tell me how I can connect to the MySQL database from some kind
> a global page, being activated no matter which page the user starts on and
> where I only need to write the different SQL statements in the individual
> pages.
> (In ASP I could do the following on the individual page:
> Set RS = Application("conn").Execute("SELECT * FROM database")
> Thank you.
> Morten
> --
> PHP Database Mailing List (
> To unsubscribe, visit:

PHP Database Mailing List (
To unsubscribe, visit:

Reply via email to