Reputation: 221
I'm writing a functions.php file...now, some functions must access the db. I have a db_connect.php file which contains the connection script. I've included it in functions.php with:
require "sys/db_connect.php";
but how to use the connection script ($con) inside
function a() {
...
}
function c() {
...
}
and so on? I've tried already setting $con variable as global, but no success.
Upvotes: 2
Views: 743
Reputation: 3461
There are three ways to do this, either accessing the value using $GLOBALS
, declaring it as a global variable or passing it as a parameter
1st way:
include 'db_connect.php';
function a() {
$link = $GLOBALS['con'];
// you can assign $GLOBALS['con'] or use it as a normal variable
}
2nd way:
include 'db_connect.php';
function a() {
global $con;
// then use it as a normal variable
}
3rd way:
function a($con) {
// use the variable
}
Read more about variable scopes here
Upvotes: 1
Reputation: 101
If you have assigned a variable $con in db_connect.php outside any functions as follows:
//----------
//sys/db_connect.php
//----------
$con = 'my connection script'; //You don't need to put global here
Then you can use $con in functions a() and c() in another php file as follows:
//----------
//other_file.php
//----------
require 'sys/db_connect.php';
function a(){
global $con; //global allows $con from above to be used in this function a()
print_r($con); //This line just for testing purposes!
}
function b(){
global $con; //global allows $con to be used in this function b()
print_r($con); //This line just for testing purposes!
}
Upvotes: 0
Reputation: 10617
I do this:
// sys/db_connect.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// functions.php
<?php
require 'sys/db_connect.php';
/* you can even close the connection and reopen it this way
$db = db(); $db->close(); $database = db(); */
function a() {
$db = db();
}
function c() {
$db = db();
}
?>
Upvotes: 0
Reputation:
This structure should work. Note where the global
declarations appear. I'd normally pass the $con variable into the function as an argument rather than using it as a global
, though.
dbconnect.php
<?
$con = mysqli_connect("blah","blah","blah","blah");
?>
functions.php
require('dbconnect.php');
function a() {
global $con;
...
}
function c() {
global $con;
...
}
Upvotes: 0
Reputation: 79024
function a($db) {
//do something with $db
}
function c($db) {
//do something with $db
}
$result = a($conn);
$something = c($conn);
Upvotes: 2