Page 1 of 1

Database class advice

Posted: Wed Jun 08, 2005 3:16 pm
by therat
I have started to create a database class to reuse in various places. I have taken what I have so far from a couple of classes found on the net. Am I going in the right direction, this only has the connec function in it so far but will eventually contain the fetch rows, last insert functions among others. Comments appreciated.

Code: Select all

<?php

class db {

    var $dbLink;


//Constructor
    function connect($dbHost, $dbName, $dbUser, $dbPasswd) {

        $mtime = microtime();
        $mtime = explode(" ",$mtime);
        $mtime = $mtime[1] + $mtime[0];
        $starttime = $mtime;

        $this->dbLink = mysql_connect ($dbHost, $dbUser, $dbPasswd);

        if ( $this->dbLink )
        {
            if ( $dbName !="" )
            {
                $this->dbname = $dbName
                $dbselect = mysql_select_db ($this->dbName);
                
                if ( !$dbselect )
                {
                    mysql_close( $this->dbLink );
                    $this->dbLink = $dbselect
                }
            }

            $mtime = microtime();
            $mtime = explode(" ",$mtime);
            $mtime = $mtime[1] + $mtime[0];
            $endtime = $mtime;

            $this->sql_time += $endtime - $starttime;

            return $this->dbLink;
        }
        else
        }
            $mtime = microtime();
            $mtime = explode(" ",$mtime);
            $mtime = $mtime[1] + $mtime[0];
            $endtime = $mtime;

            $this->sql_time += $endtime - $starttime;

            return false;
        }
    }

?>

Posted: Thu Jun 09, 2005 7:52 am
by thomas777neo
Looks Fine

Leave out the timing though.Put more error checking aswell.

I have no idea where you get the $this->sql_time variable from. You forgot a ; on line 28.

Just a tip, your connect function is not a constructor. The constructor of a class usually has the same name as the class. Or in php5, _construct as the function name.

Otherwise, not bad as all. Try and have a look at someting like ADOdb. So that you can connect to any database and not just mysql.

Posted: Thu Jun 09, 2005 10:22 am
by pickle
Ya, get rid of the timing - that's a lot of overhead.

Returning values from your constructor is probably a personal choice, but I would either return true or false, I wouldn't return the DB link. In my opinion, objects should be encapsulated - if you want to get a value from them, write a get() method.

You're condition if (!$dbselect) could cause you some problems. You should return false if that happens. I wouldn't overwrite $this->dbLink either, though there shouldn't be a situation where you keep using the object after a db selection has failed.

Otherwise, seems pretty straightforward.

Posted: Thu Jun 09, 2005 12:47 pm
by therat
Thanks for the comments. Just wanted to know I was on the right track.