Page 1 of 1

Function global

Posted: Sat Dec 27, 2008 1:48 pm
by Cirdan
I have this code:

Code: Select all

 
require 'config.php';
 
function mysqlConnect()
{
    global $db_host, $db_username, $db_password, $db_database;
 
    $connection = mysql_connect($db_host, $db_username, $db_password)
                    or die('Failed to connect to MySQL. '.mysql_error());
    
    $db = mysql_select_db($db_database, $connection)
            or die('Failed to select the database.');
            
    return $connection;
}
On my local server, this works perfectly fine. On the dev server it will not get the $db_* variables from the config file. Is there a php setting I need to change to get this to work? AFAIK, this is a documented feature in the php manual. Don't make me explain, but my local server is php4 because our production server is php4...but our dev server is php5.

Re: Function global

Posted: Sat Dec 27, 2008 2:02 pm
by sergio-pro
Hi,

Is your config.php file in lowercase?
This sometimes happens when smth works ok on local (windows - case-insensitive os) and not working on server (usually case-sensitive linux).

I'd also advise not to use global vars - as it is bas coding style.
In this case you can define constants:
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'my_db');
define ('DB_USER', 'my_name');
define ('DB_PASS', 'my_pass');

Re: Function global

Posted: Sat Dec 27, 2008 2:02 pm
by cptnwinky
I'm not sure why the global declaration isn't working but a quick workaround would be to pass those variables to your function...

Code: Select all

 
function MySQLConnect($db_host, $db_username, $db_password, $db_database) {
     $connection = mysql_connect($db_host, $db_username, $db_password)
                     or die('Failed to connect to MySQL. '.mysql_error());
    
     $db = mysql_select_db($db_database, $connection)
             or die('Failed to select the database.');
            
     return $connection;
}
 
require('config.php');
$conn = MySQLConnect($db_host, $db_username, $db_password, $db_database);
 

Re: Function global

Posted: Sat Dec 27, 2008 2:04 pm
by Cirdan
Yes, everything is lowercase. For some reason now tho, my local server can't select the database. This is really strange, I didn't change anything.

Re: Function global

Posted: Sat Dec 27, 2008 2:18 pm
by cptnwinky
You have to call MySQLConnect just as I did above, passing the variables to it.

Code: Select all

 
$conn = MySQLConnect($db_host, $db_username, $db_password, $db_database);
 

Re: Function global

Posted: Sat Dec 27, 2008 2:24 pm
by Cirdan
Ok thanks guys, I got it working.

Re: Function global

Posted: Sat Dec 27, 2008 2:37 pm
by cptnwinky
No prob.