Page 1 of 1

[solved] class ( connection wont work )

Posted: Wed Dec 08, 2004 3:28 pm
by ol4pr0
Oke i have this class

had me an other one. but that didnt work so came up with this.
However i cant seem to figure out why it wont connect.

Code: Select all

<?php
class database {
    var $link;   
    var $errors = array();

    function connect( $host, $name, $pass, $db ) {
        $link = mysql_connect( $host, $name, $pass );
        if ( ! $link ) {
            $this->setError("Couldn't connect to database server");
            return false;
        }

        if ( ! mysql_select_db( $db, $this->link ) ) {
            $this->setError("Couldn't select database: $db");
            return false;
        }
        $this->link = $link;
        return true;
    }
    // and some more ofcourse
Executing it.

Code: Select all

$dl = new database( );
$dl->connect( "***", "****", "", "test" ) or die ("cant connect");

#$dl->connect( "localhost", "root", "", "test" ) or die ( $dl->getError() );
# as this didnt return a error i put it cant connect manually to see where it went wrong.

Posted: Wed Dec 08, 2004 3:31 pm
by protokol
Look at line 13. You'll see that you are accessing $this->link before setting the value ;-) Change it to $link and you'll be cool.

Posted: Wed Dec 08, 2004 3:33 pm
by kettle_drum

Code: Select all

$link = mysql_connect( $host, $name, $pass );

//needs to be

$this->link = mysql_connect( $host, $name, $pass );

//or change

if ( ! mysql_select_db( $db, $this->link ) ) {

//to

if ( ! mysql_select_db( $db, $link ) ) {

Posted: Wed Dec 08, 2004 3:35 pm
by protokol
I would use the following because he probably doesn't want the link set yet until he actually gets a valid connection:

Code: Select all

<?php
if ( ! mysql_select_db( $db, $link ) ) {
?>

Posted: Wed Dec 08, 2004 3:39 pm
by ol4pr0
Hmm tried both. and still no luck

a regular connection without having it inside a class works fine.

[edit]

My bad. thanks both of you.

Works nicely now :)

Posted: Wed Dec 08, 2004 3:43 pm
by protokol
Post your new code so we can debug further.