Reputation:
I have a php page with my mysql connection string ($conn) at the top and then I have created a function that I will run later on down the page.
my function has it's own arguments but as I am going to be creating many functions I don't want to have to put my $conn in everyone but unless I do, I cannot connect to the database within the function
For example,
function one ($var1, $var2) {
//mysql stuff here
}
Does not work because it cannot find the $conn
function one ($var1, $var2, $conn) {
//mysql stuff here
}
Does work because it has the $conn variable passed in the function
So is there anyway I can create my functions without having to put the $conn in them all?
Upvotes: 2
Views: 846
Reputation: 2286
You can use the global
keyword to access $conn
from inside a function.
function one ($var1, $var2) {
//mysql stuff here
global $conn;
}
See notes on Variable scope for more information.
I suggest using a Constant instead of a variable to hold your connection string:
Upvotes: 2