Hello All:

I am some difficulties getting some database variables from an included file to my mysql connection. Here is what i have:

file one Called config.inc.php:

session_register("client_id");
$_SESSION['client_id'] = $_SESSION['SESS_ACCT_ID'];// 
$club_id=$_SESSION['client_id'];
ob_start();
include('../../../page_title.php');
ob_end_clean();
include('../../../datalogin.php');


if (!defined('DEFAULT_HOST')) define('DEFAULT_HOST','localhost');
if (!defined('DEFAULT_USER')) define('DEFAULT_USER',$account_user);
if (!defined('DEFAULT_PASS')) define('DEFAULT_PASS',$account_pass);
if (!defined('DEFAULT_DB')) define('DEFAULT_DB',$account_db); 

the variables inside the define() are from the included datalogin.php.

Now, from my second file:

include('config.inc.php');
$link = @mysql_connect(DEFAULT_HOST, DEFAULT_USER, DEFAULT_PASS);
    //var_dump($link);

if (!$link) {
    die('Could not connect: ' . mysql_error());
}

# mysql_query("SET SESSION time_zone = '-0:00';");
#mysql_query("SET NAMES 'utf8'", $link);

$db_selected = mysql_select_db(DEFAULT_DB, $link);
if (!$db_selected) {
    die ("Cannot use database: ".DEFAULT_DB.mysql_error());
}

I'm unable to pass the variable to both:

$link = @mysql_connect(DEFAULT_HOST, DEFAULT_USER, DEFAULT_PASS);

and

$db_selected = mysql_select_db(DEFAULT_DB, $link);

However, I can echo (or print) to screen of:

DEFAULT_DB
DEFAULT_HOST
DEFAULT_USER
DEFAULT_PASS

Any ideas as to what is happening with the lost of the values in the db connection string

Try changing include('../../../datalogin.php'); to require_once('../../../datalogin.php'); to make sure that the file is actually being included.

A couple of things:

  • session_register() appears to be a deprecated function. You don't need to use it. Using only
    $_SESSION['key'] = 'value';
    will suffice if you run a PHP version from less than a long time ago ;).

  • Should you not start a session using session_start() in the first line of your script, so that your session actually works?

  • About the following code:

    ob_start();
    include('../../../page_title.php');
    ob_end_clean();

    Any output in the file that you are including here will not get printed. Why are you using output buffering here, anyway? :)

  • What happens if you remove the @ from your mysql_connect() function? Does an error get printed to your screen?

  • Why are you even using the define() function to define your database connection info? As you seem to already have them placed inside variables. Why don't you just use your $account_user vars and alike?

Member Avatar for diafol

As mentioned above, why are you defining constants using variables? Constants are erm... constant, so not variable. If you can hard-code a value into your code and it should never change, then it's a constant.

Most of my setups using constants either have a constants.php or config.php file and I require that. If you find that you're requiring/including that several times, then maybe you need to look at the way you're structuring your needs.

require_once 'constants.php';

May help you here - that way you don't have to worry about whether your constants have already been declared - as long as they're always declared in the same file, that is.

Thank you both for your input.
Hielo, changing from include() to require_once() appears to change nothing.
Minitauros,
I removed the code below, I actually meant to comment it out

ob_start();
include('../../../page_title.php');
ob_end_clean();

Removing the @ from mysql_connect() function does nothing either. I have tried simply passing the variables directly to the connection function, I experienced the same outcome. No value is been past. Again, when I echo those variables I'm able to see them.

A bit troubled!

Doing away with the constant() and then passing variables to the connection function still does not work. I'm getting:

Could not connect: Access denied for user 'username'@'localhost' (using password: NO)

this is what I have

    require dirname(__FILE__) . '/config.inc.php';
    //require_once('config.inc.php');
    session_start();
    $_SESSION['client_id'] = $_SESSION['SESS_ACCT_ID'];// 
    $club_id=$_SESSION['client_id'];
    include('../../../datalogin.php');

    echo $club_id; // I am able to see this value
    echo $account_user; // I am able to see this value
    echo $account_pass; // I am able to see this value
    echo $account_db;// I am able to see this value


    $link = mysql_connect("localhost", $account_user, $account_pass);      
    if (!$link) {
    die('Could not connect: ' . mysql_error());
    }


    $db_selected = mysql_select_db($account_db, $link);
    //  var_dump($db_selected);
    if (!$db_selected) {
    die ("Cannot use database: ".$account_db.mysql_error());
    }

if I however hardcode the following variables:
$account_user="*****************";
$account_pass="*****";
$account_db="tablete7_NEWYORKT8813";

the db connection() works....But this is not an option for the application, I need to get the variables from the included file.

Any thoughts as to what I'm missing!

Member Avatar for diafol

you don't show the code for where the vars are dimensioned. Show that.

Diafol, I am assuming you're asking for the code of the included datalogin.php. if so, the content is as follows:

   if(........)
    {
    }
    elseif($accountid_var =="744821" || $club_id =="744821" )//-------"Allen Matt Table Tennis" Account Dynamically inserted on "23-06-13 @ 08:22:41" 

    {

                                                                /*------------------*/

                                                            //CHANGE THE VARIABLES HERE FOR PASSWORD AND DATABASE USER NAME
                                                            $account_pass="*****";
                                                            $account_user="******";
                                                            $account_mster_db="tablete7_ttproclubs_clients";
                                                            $account_db="tablete7_ALLENMAT744821";
                                                            $club_accountid_raw=""; 
                                                            $cal_user_name="********";
                                                            $countries_db="tablete7_countries";
                                                            $countries_db_user= $cal_user_name;
                                                            //FAQ
                                                            $admin_username="*****";
                                                            $admin_password="*******";

                                                            /*------------------*/
   }

The code above use the variable $club_id (which it receives when the file is included) to perform the if and else conditional statement.

Member Avatar for diafol

Hold on, this looks like you're using separate DB user/pw for each user on your site. Is that what you're doing?

Yes, I'm assigning different database connection information based on an account id in the if and else conditional statement. All databases are on the same server!

Member Avatar for diafol

Why? You're not a reseller? I would think that you need to use just your own 'safe' credentials for all dbs. You don't need to provide your users with their own DB credentials. Login credentials fine, but I can't see the advantage of the other. If a db is assigned to an user in the db, that should be sufficient to ensure exculsivity.

Setting up user db rights for each new user must be a pain. Maybe I'm missing something.

Diafol, thanks for the follow-up. I'm developing a project concepts for my favority sport industry, Table Tennis. Each user will be accessing an account with large number of tables relating to that account only. So the most effecient way of achieving this is with a unique database for each account.

I'm not talking about one user per account but multiple users per account. I have already constructed an algorythim that gathers all necessary information at the creation of each new accounts and automatically builts and sets up all necessary rights --no pain at all( done with just two clicks of the mouse). This part is working without a problem. By the way, all database connection information in the include is for system use, it is not provided to the user/account holder. As you have noted in you post above, login credentials is all that is required of each user/account holder to access their account and related data.

My issue in this Post concerns a new module I'm adding to the program and I'm simply wanting to call my Account Validating script (the file with the database information), get the database information and then make the correct connection to the associated db.

Most importantly, if I can get the dbname from the file and pass it to the connection(), I think that would be fine. This is were my problem lies. Why can't I get those variables from that include file into the db connection function?

Any further thought, is appreciated!
Mossa

Member Avatar for diafol
elseif($accountid_var =="744821" || $club_id =="744821" )//-------"
    echo "CHosen 744821<br />";

It's that bit that's probably causing the issue. Why not in your main page:

echo "ACCOUNT USER: $account_user ; ACCOUNT PASS: $account_pass<br />";
$link = mysql_connect("localhost", $account_user, $account_pass);      

Just place a few simple strategic echoes to see where your variable is getting set (if at all).

By the way, all database connection information in the include is for system use, it is not provided to the user/account holder.

If it's for system use only, why not use a single username/password combo for all databases? It's just the database name that needs to be configurable.

Pritaeas, even trying to configure only the db name gives the same outcome --whereas the the conn () is not getting the db name var.

Giving Diafol suggestion a try; however, please clarify the reason for echoing:

echo "CHosen 744821<br />";

after the elseif

Still hitting the same barrier.
getting error:

 Could not connect: Access denied for user 'correctUsername'@'localhost' (using password: NO)

The echoing of the variables before the connection () and deb select () outputs the correct values

      ACCOUNT USER: correctUsername ; ACCOUNT PASS: correctPass
        ACCOUNT DB: tablete7_ALLENMAT744821

I am at my "wits-end"....any further thougths!

Access denied may be caused by your script. After adding the new user and giving him priviliges on the database, do you also "FLUSH PRIVILIGES" ?

No Flusing is done!
Now, my only configuration to be passed to the connect() is the db name. I'm hard coding the user name and password and building the connect() like so:

    require_once('../../../datalogin.php');

$account_user_hrd="user";
$account_pass_hrd="pass";
//$account_db // from the include file
echo "ACCOUNT USER: $account_user  ACCOUNT PASS: $account_pass<br />";
     $link = mysql_connect("localhost", $account_user_hrd, $account_pass_hrd);

With the above, the connection denied error disappears
now, with:

echo "ACCOUNT DB: $account_db<br />";

$db_selected = mysql_select_db($account_db);
//var_dump($db_selected);
if (!$db_selected) {
    die ("Cannot select db: ".$account_db.mysql_error());
}

I get the following error:

Cannot delect db: No database selected
Member Avatar for diafol

I am at my "wits-end"....any further thougths!

Ho, ho! It's bound to be something simple. Try using these connection details in phpmyadmin to see if they work.

But think about this carefully. Both pritaeas and myself have advised you to use a single 'system' un/pw. I really think you're making this harder and more complicated than it really needs to be. Anyway if phpmyadmin works for you, I can't see why it shouldn't for access via php.

Giving Diafol suggestion a try; however, please clarify the reason for echoing:
echo "CHosen 744821<br />";
after the elseif

That's simply to show that the correct branch of the conditional statement was being run. If the vars in the connection script were blank, you'd be none the wiser as to why. This way, at least you know the conditional statements are running as expected. This has been confirmed by echoing out before running the connection statement.

So we seem to have narrowed down the issue to the connection itself. This may seem like a stupid question, but are you querying the right connection? I'm assuming that you have a testing db server (local?) and a remote db server.

I also notice here that you're not using a password:

(using password: NO)

If not, this is pretty unsecure. But you do seem to be passing a password in your code. So, what's going on with that?

Try using these connection details in phpmyadmin to see if they work.

this works fine!

This may seem like a stupid question, but are you querying the right connection?

Not a stupid question, but yes! Remember the connection is successful if:

$account_db ="dbname";//Hard coded value representing the very value attempting to pass from the included file

it fails only when we are calling the variable from the file. This verifies that the correct connection is being queried.

I also notice here that you're not using a password:

(using password: NO)
If not, this is pretty unsecure. But you do seem to be passing a password in your code. So, what's going on with that?

this message is only printed when the password variable is being passed from the included file. Absolutely, there is a password required for access.

Member Avatar for diafol

Just re-read your posts again - sorry I seemed to miss the fact that you had already tested with echoes. :(

OK:

$account_pass="*****";
$account_user="******";
$account_mster_db="tablete7_ttproclubs_clients";
$account_db="tablete7_ALLENMAT744821";
$club_accountid_raw="";
$cal_user_name="********";
$countries_db="tablete7_countries";
$countries_db_user= $cal_user_name;
//FAQ
$admin_username="*****";
$admin_password="*******";

This seems to be giving all the info for connection details, but it's hard-coded for some reason. I would assume that you'd use the system details to get the user's connection credentials from a db table when s/he logs in. That way you don't need to hard-code anything much:

USERS
user_id | username ... | login_password | db_id

DB_DETAILS
db_id | db_name | db_user | db_password | country_id 

Just an idea - then you don't need all those conditional branches.

You query the db_details with the db_id (from when the user logs in) and get the db_* connection details - which can be retrieved from a function (or class) on every page or stored in session vars (personally I don't like to save this sort of stuff in session, but it'll work).

The concept as you write is what I'm doing, But the connection details are dynamically appended to the file which is included on the necessary pages. Essentially, the hard-coding of the db connection values is dynamically appended to the file at the initiation of the account. Perhaps, keeping this info in a separate db table and using similar logic to retrieve and pass appropriate connection values would be better. I may consider this later. I'm still vexed as to why in this particular instance (the subject of this post thread), I'm not able to get the variable from the included file to the db_connect().

Member Avatar for diafol

So let me get this right, you're appending

a conditional branch with variable declarations to the datalogin.php file when somebody creates a DB?

Erk! That's complicated - but anyway, back to the issue. You're initializing the password variable within the datalogin.php (and it's OK) and this is passed to the connection statement in the container page and it's still fine, but the connection fails, although these details work fine for phpmyadmin. ALso when you hard code these values into the connection statement, it works fine. I'm assuming that the password just contains the usual characters (alphanumeric)?

Could the stored variable value have any whitespace attached to it?

Could the stored variable value have any whitespace attached to it?

I thought the issue of white spaces may be causing the problem, so stripped it all var like so:

 $rmve_sp = preg_replace('/\s+/', '', $account_db);

That still wasn't the issue!

I just tried another angle. Keeping in mind that the logic is that on successful user login, the user's account id ($club_id) is passed to datalogin.php which then performs a series of condition verification using the $club_id. Wherever there is a match it makes all variables under that condition available. Now the account id in its variable form is defined with a session variable like: $club_id=$_SESSION['SESS_ACCT_ID'];

Now it appears the session variable is not being registered. here is what i have

session_start();
$club_id=$_SESSION['SESS_ACCT_ID'];
//var_dump($_SESSION['SESS_ACCT_ID']);
   include('../../../datalogin.php');

So if I replace the session variable with a hard code value like so:

   $club_id="8813"; //$_SESSION['client_id'];

I am able to pass the include file's variables to the db connection statement. so, essentially this:

    $link = mysql_connect("localhost", $account_user_hrd, $account_pass_hrd);
    $db_selected = mysql_select_db($account_db);

it works!

HOWEVER, the mistery continues; if I echo $_SESSION['SESS_ACCT_ID'], it prints the correct value to screen, BUT it will not be defined with $club_id (ie:

  $club_id=$_SESSION['SESS_ACCT_ID']; 

)

Quite vexing...

Member Avatar for diafol

OK, you've made quite a few changes now, so I'm a bit confused as to how this all sits together. SO if you could post the updated code.

ANyway:

session_start();
$club_id=$_SESSION['SESS_ACCT_ID'];
echo "CLUB: $club_id <br /> SESS_CLUB: {$_SESSION['SESS_ACCT_ID']}";

Try that to see what you get.
Is $club_id set again anywhere in the included file? That is, I'm assuming they're all comparisons (==) and not assignments (=).

Diafol, just step a way from my computer. I will post the updated code in a few hrs.
Again, I appreciate your time as i navigate throughout this issue.

Best,

Member Avatar for diafol

No prob. Will be back tomorrow night, unless somebody else can help you out in the meantime.

Hello Diafol and All:

I think the real problem is with the session variable that is being passed to the file containing all the db info. To recap, here is what is happening:

For file one, I have the following:

defining these variables like below and passing into the included conn.php works

          $club_id=744821";
          $accountid_var="744821";

defining these variables with a session variable like below and passing into the included conn.php DOES NOT WORK!!!!

          session_start();          
          $club_id=$_SESSION['SESS_ACCT_ID'];
          $accountid_var=$_SESSION['SESS_ACCT_ID'];

          include_once('conn.php');

I am able echo the session like below and it is available.

        echo "CLUB: $club_id <br /> SESS_CLUB: {$_SESSION['SESS_ACCT_ID']}<br />";

        if (!defined("DEFAULT_HOST")) define("DEFAULT_HOST", "localhost");
        if (!defined("DEFAULT_USER")) define("DEFAULT_USER", $account_user);
        if (!defined("DEFAULT_PASS")) define("DEFAULT_PASS", $account_pass);
        if (!defined("DEFAULT_DB")) define("DEFAULT_DB", $account_db);

        $link = mysql_connect(DEFAULT_HOST, DEFAULT_USER, DEFAULT_PASS);
        //var_dump($link."<br />");
         if (!$link) {
        die('Could not connect: ' . mysql_error());
        }
        # mysql_query("SET SESSION time_zone = '-0:00';");
        //mysql_query("SET NAMES 'utf8'", $link);      
        //echo "ACCOUNT DB: $account_db<br />";

        $db_selected = mysql_select_db(DEFAULT_DB);
        //var_dump($db_selected);
        if (!$db_selected) {
        die ("Cannot connect to a database: MSG Option.inc: ".DEFAULT_DB.mysql_error());

For file 2 (containing the db info)

    if($accountid_var =="8813" || $club_id =="8813" )//-------"New York Table Tennis" Account Dynamically inserted on "20-06-13 @ 09:38:51" 

    {

    /*------------------*/

    //CHANGE THE VARIABLES HERE FOR PASSWORD AND DATABASE USER NAME
    $account_pass ="pass";
    $account_user ="username";
    $account_mster_db ="tablete7_ttproclubs_clients";
    $account_db ="tablete7_NEWYORKT8813";
    $club_accountid_raw =""; //club account id needs to be hard coded for auto membership reminder
    $cal_user_name = "username";
    $countries_db ="tablete7_countries";
    $countries_db_user = $cal_user_name;
    //FAQ
    $admin_username ="admin";
    $admin_password ="pass";


    } 
    /***DO NOT REMOVE OR MODIFY ANYTHING BELOW***/

    elseif($accountid_var =="744821" || $club_id =="744821" )//-------"Allen Matt Table Tennis" Account

    Dynamically inserted on "23-06-13 @ 08:22:41" 

    {
    /*------------------*/

    //CHANGE THE VARIABLES HERE FOR PASSWORD AND DATABASE USER NAME
    $account_pass=pass";
    $account_user="username";
    $account_mster_db="tablete7_ttproclubs_clients";
    $account_db="tablete7_ALLENMAT744821";
    $club_accountid_raw=""; //club account id needs to be hard coded for auto membership reminder
    $cal_user_name="username";
    $countries_db="tablete7_countries";
    $countries_db_user= $cal_user_name;
    //FAQ
    $admin_username="admin";
    $admin_password="pass";


    } 

    /***DO NOT REMOVE OR MODIFY ANYTHING BELOW***/

    ###INSERTTEXTMARKER####
    else
    {
    error_reporting(E_ALL); 

    }

So the question, can anyone tell me why I'm not able to get the session variable inside my conn.php file. BUT am able to get the hardcode variable.

I really would appreciate some thoughts on this!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.