blogo blogo - 4 months ago 4
PHP Question

PHP database connection inside if statement

I am trying to connect to a database if a condition inside an if statement is met:

if ($check == 1){
mysql_select_db($database_lg, $lg);
$query = "SELECT token FROM tbltokens WHERE name = '$name'";
$result = mysql_query($query, $lg) or die(mysql_error());

It works just fine if I put this same code outside the if statement. As soon as I wrap it in the if statement I get the error: "Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in..." The error applies to lines 2 and 4 in the code.


  1. I found a similar question where the solution was to require the database connection inside the if statement, which I have done.

  2. I realize that mysql_* functions are deprecated. The are tons of mysql_* functions on this site which I have to live with for a while longer.

Thank you in advance.

connect.php mentioned in the code above looks like this:

$hostname_lg = "xxx";
$database_lg = "xxx";
$username_lg = "xxx";
$password_lg = "xxx";
$lg = mysql_pconnect($hostname_lg, $username_lg, $password_lg)
or trigger_error(mysql_error(),E_USER_ERROR);

This may not be very relevant though as the connection succeeds when the if statement isn't there. It only fails when inside an if statement as in the example.


Is your if statement inside a function? Each function has its own scope in php. The error you're receiving is making it seem as the parameters you pass in, $database_lg, $lg are not defined, meaning they're probably out of scope. You should make sure the variables $database_lg, $lg are visible by calling global:

if ($check == 1){
    global $database_lg; 
    global $lg;

Also, put require_once at the top of your code(not in the if statement).