guitarlass
guitarlass

Reputation: 1617

Trouble connecting to the database

I'm trying to connect to 2 databases. One of them is a remote database. Once i connected to the remote database i had trouble with the one that existed, it gave me 'supplied argument is not valid ' on mysql_fetch_array() . So i changed my database class a bit and tried to make it work. But i still get errors :(. Its not grabbing $connection variable. i get "undefined variable connection". this is my connection class. Please help me out. Appreciate your help.

global $connection;

class Database{

function __construct()
{
    $this->open_connection();
}

public function open_connection()
{

    $connection = $this->connection= mysql_connect(SERVER,UNAME,PASSWORD);

    if(!$this->connection)
    {
        return false;
    }

    if(!mysql_select_db(DB_NAME,$this->connection))
    {
        return false;
    }
    return true;
}

public function close_connection()
{
    mysql_close($this->connection);
}
 //open_connection();
 }

$database = new Database();

and in another page:

$result=mysql_query($query,$connection);        

while ($rec = mysql_fetch_array($result)) ... etc

p.s all constants and other variables are correct.

Upvotes: 1

Views: 96

Answers (3)

machineaddict
machineaddict

Reputation: 3236

the "global $connection;" MUST be inside "open_connection" method or use @peipst9lker method

Upvotes: 0

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

Hmm... Well, it looks like you are getting an undefined error thrown because you are calling global $connection at the top of the class file, and it hasn't been assigned a value.

It looks like you are establishing $connection inside of the open_connection() method... Are you establishing $connection in some included file that you haven't mentioned?

Try removing the first line of code, perhaps?

Upvotes: 0

peipst9lker
peipst9lker

Reputation: 605

Using a global variable in a class is like death. You could provide a class field for the connection link

$this->connection = mysql_connect(...);

And outside your class

$result = mysql_query($sql, $object->connection);

I'd also suggest you to use the existing mysqli class.

Upvotes: 1

Related Questions