making a global connection

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hame22
Forum Contributor
Posts: 214
Joined: Wed May 11, 2005 5:50 am

making a global connection

Post by hame22 »

Hi i have a function

db_connect() which connects to my database

Code: Select all

function db_connect()
{
 $result = mysql_connect('localhost', 'user', 'password') or exit ("can't connect to database");

 if(!$result)
  return false;
 if(!mysql_select_db('db'))
  return false;
 return $result;
}
at the moment for every query in my application i am calling the function, is there a way to make this function global so i dont have to call it all the time?.

Also wondered as I have tens of queries, could all these connections affect perfromance?

thanks in advance
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

At the top of each page

Code: Select all

<?php
$result = db_connect();
At the top of any functions:

Code: Select all

<?php
 function blahBlahBlah () {

global $result;

}
Otherwise just use $result as normal. You should only connect to the database once per session (page, including included pages).
Post Reply