Reputation: 11
I am new to php. I have one file for the connection to database "db_connection.php".
<?php
//With constants
define("DB_SERVER","localhost");
define("DB_USER","root");
define("DB_PASS","");
define("DB_NAME","db_name");
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
I also have another file called "functions.php".where i have a function for the query
<?php
function confirm_query($result_set){
if (!$result_set) {
die("Database query failed.");
}
}
function find_all_subjects(){
global $connection;
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$subject_set = mysqli_query($connection, $query);
// Test if there was a query error
confirm_query($subject_set);
return $subject_set;
}
?>
The main file where i call the function "main.php"
<?php require_once("db_connection.php"); ?>
<?php require_once("functions.php"); ?>
<?php $subject_set = find_all_subjects(); ?>
There is no problem everything works fine but can you explain how global $connection; inside "functions.php" is actually working?
Upvotes: 1
Views: 523
Reputation: 288
When you include or require PHP files in a webpage, even if you split all your code and functions in separate files, it is essentially the same if you included just one file with all the code from the separate files.
So a variable which you declare / create in "db_connection.php" works the same if you created it in the "functions.php" if you include both files in the same page.
This is why you must be careful with variable, function, etc naming if you use separate files.
Upvotes: 1
Reputation: 657
when you write that line
<?php require_once("db_connection.php"); ?>
then that behave like db_connection.php file write in that file.
then other line you write
<?php require_once("functions.php"); ?>
then that behave like you write function.php file in main.php file so that work fine..
Upvotes: 0