Domanda

Config.php :

$settings = array();

$settings['mysqlhost'] = 'localhost'; // Mysql hostname
$settings['mysqluser'] = '**'; // Mysql username
$settings['mysqlpass'] = '**'; // Mysql password
$settings['mysqldatb'] = '**'; // Mysql database

functions.php :

include_once('config.php'); 

function si_connect_db(){

    $connection = mysql_connect($settings['mysqlhost'], $settings['mysqluser'], $settings['mysqlpass']);
    $selectdb = mysql_select_db($settings['mysqldatb'], $connection);

    if($connection){
        if($selectdb){
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

Now when i do for example:

include_once('functions.php');
si_connect_db();

I am not connected... How can i do that?

È stato utile?

Soluzione

PHP variables that are declared outside of a function are not, by default, visible inside functions.


If you declare a variable outside of a function, and want it to be visible inside that function, you'll have to use the global keyword :

function si_connect_db(){

    global $settings; // Make $settings visible inside the function

    $connection = mysql_connect($settings['mysqlhost'], $settings['mysqluser'], $settings['mysqlpass']);
    $selectdb = mysql_select_db($settings['mysqldatb'], $connection);

    ...


For more informations, you should take a look at the Variable scope section of the manual.

Altri suggerimenti

You should make $settings as global variable

function si_connect_db(){
   global $settings;

http://php.net/manual/en/language.variables.scope.php

You'd have to use the global keyword in your function to let the function know that $settings is global.

Better instead to define global constants using define() e.g.:

define(MYSQLHOST, 'localhost');

That way you don't have to use the global keyword to define your config settings.

This is a scoping issue. Essentially $settings is not visible to the si_connect_db function.

What you should do is pass $settings as a parameter to the si_connect_db function. This can be accomplished with global instead, but using globals is bad practice and frowned upon for many reason. Testability, maintainability, readability and generally OOP design (as it breaks encapsulation).

function si_connect_db($settings) {
    // do stuff here
}

Then:

include_once('functions.php');
si_connect_db($settings);

You should include your setting file inside the function. Avoid the use of global scope for God's sake. I'm suggesting you this also because the setting file is called if you need to connect only. With my method you could also forget about including the setting file in every app's page every time you need to connect. The use of the keyword global is just an hack.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top