A
A
Artqookie2011-07-22 20:28:36
PHP
Artqookie, 2011-07-22 20:28:36

Connect to the database from functions (PHP)

The question is probably very noob, but I do not know and cannot find a way how to solve it correctly . It consists in the following.

There is, for example, such a hierarchy of files on the server:

/
     index.php
     db.php
+  /fns
            functions.php
            ...
+  /profile
            index.php
            ...


Each of the index.php accesses the database through the db.php include, and functions.php is also included in them. In functions.php I need to use database access from db.php.

Hence the question itself: how? How to call $db connection inside functions that are in functions.php? I immediately tried to include the connection file to the database in the functions themselves, but since it is not recommended to use direct paths in the includes, but only relative ones, then naturally there is a problem with incorrect paths.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
T
Timur Shemsedinov, 2011-07-22
@MarcusAurelius

Options:
1. Make a static class db in db.php and make all the "public static function" functions in it, for example: db::connect, db::query, db::freeCursor, db::getLasInserttId, etc. and then it will not be necessary at all to transfer the pointer to the database object to other modules.
2. Make a FrontController in your project - that is, a single entry point, redirect all URLs to it and instead of later connecting all modules in each php file - connect them once centrally from one file, and there with problems will not.
3. Make a variable $db = db::connect(dbHost,dbName,dbUser,dbPassword); just declare it not inside the function, but in the body of the php code and then in all functions where you need to access write global $db; and then $db->MethodName…
4. Read something about scopes in PHP
5. Or take a ready-made framework where these tasks are solved, and when you get sick of the engine, and this will happen sooner or later, then to this time, you will already figure out how not to do it)

V
Vitaly Zheltyakov, 2011-07-23
@VitaZheltyakov

“Each of the index.php accesses the database through the db.php include, and functions.php is also included in them. In functions.php I need to use database access from db.php.”
- It seems to me that you are either using very old books, or video tutorials bydlocoder Evgeny Popov. No offense…
Add the following functions at the top of index.php:
// Процедура записи в лог фаил для записи ошибок
function writelog($typelog, $log_text) {
$log = fopen('logs/'.$typelog.'.txt','a+');
fwrite($log, "$log_text\r\n");
fclose($log);
}
// Процедура подключения к базе данных. Вызываете её, когда Вам нужно подключение
function dbconnect() {
global $database;
if (!isset($database)) {
$database = mysql_connect ("localhost", "**","****");
mysql_select_db("***", $database);
}
}
// Функция выполнения запросов с логированием ошибок
function sql_query($query) {
$return = mysql_query($query);
$error = mysql_error();
if ($error=='') {
return $return;
}
else {
writelog('sql_error', date("y.m.d H:m:s")."\t".$error);
return false;
};
}

D
DorBer, 2011-07-22
@DorBer

For example a singleton or just a static method. As a result, there may be something like DB::getConnection();

A
Artqookie, 2011-07-22
@Artqookie

Thanks for all the advice, especially. Decided with a singleton.

D
Dan, 2014-05-11
@golotyuk

If you use mysql_connect and mysql_select_db to connect, then you don't need anything to work with the database from functions. The main thing is that the connection (db.php) is enabled before functions.php. Feel free to use mysql_connect inside functions (it will use the global connection resource, which will be available everywhere).
I advise you to read more on your questions:
- PHP and MySQL
work - Code organization

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question