Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Accessing MySQL Db connection from within a function

Status
Not open for further replies.

roardood

Technical User
Apr 11, 2002
11
ZA
This is probably a really newbie question, but I can't search tek-tips at the moment, so I am going to have to post it.

I am writing a script where I establish a connection to a mysql db server within the main body of my script. Later I call a homemade function that runs a query via the already established connection.

I know that if I run mysql_query in the main body of the script it will use the last created connection by default, but I am wondering how the scope issues involved with a function will affect mysql_query e.g. if I call mysql_query within the homemade function, will I need to include a reference to the resource identifier of the previously established mysql connection, or will PHP be able to identify it on its own?

Tx

RD
 
When you issue mysql_[p]connect(), explicitly capture the return to a variable. And make that variable an element of the superglobal array $GLOBALS. (
Then in your function which performs queries, use the optional parameter of mysql_query() that explicitly tells it what database connection handle to use.

In fact, you can make your database connection withing function. If you make an assignment to $GLOBALS from within a function, that value is available to the rest of the script.

For example:

Code:
function my_mysql_connect ()
{
   $GLOBALS['database_handle'] = mysql_connect('myserver', 'myuser', 'mypassword');
}

function my_mysql_query ($query)
{
   mysql_query ($query, $GLOBALS['database_handle']);
}
Want the best answers? Ask the best questions: TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top