Welcome to our forums...

If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed.

Forum Statistics

  • Forum Members:
  • Total Threads:
  • Total Posts: 1
There are 1 users currently browsing forums.
Reply
  #1  
Old 03-16-2006
Smart College Student
 
Join Date: Jan 2005
Location: Ohio
Age: 21
Posts: 214
Rep Power: 6
Vouksh is on a distinguished road
Better MySQL Class

I know the previous post was a MySQL class, but as I was looking through it, it was sort of.. ineffient. I wrote one that allows me to do things quickly. It keeps things together, and builds queries for you.
php Code:
    <?php/** * MySQL Class * @Copyright: Vouksh.info 2005 * @Description: A class to connect to a mysql database, and some stuff like select, delete, update, ect * @TODO: Optimize and secure it. Possibly cache it, but I dunno. */class mysql{    var $connected = NULL;    var $mdc = NULL;    var $qnum = 0;    /**     * Connects to the MySQL server and selects the database.     *     * @param string $sDb     * @param boolean $bNc     * @return mysql     */    function mysql($sDb, $bNc=false)    {        if(!$bNc)        {            $this->mdc = mysql_connect("localhost", MYSQL_USER, MYSQL_PASS) or $this->error();            mysql_select_db($sDb, $this->mdc);            $this->connected = true;        }        return true;    }    /**     * Closes the MySQL connection.     *     * @return boolean     */    function close()    {        // Check to see if we're connected first..        if($this->connected !== true)        {            // If we're not connected, return false!            $ret = false;            echo "You must connect before you close retard!";        } else {            // W00t, we're smart and connected first!            mysql_close($this->mdc) or $this->error();            $ret = true;            echo '<!-- queries: '. $this->qnum .' -->';        }        // Do we get and A or an F?        return $ret;    }    /**     * Runs a MySQL "SELECT * FROM" command.     *     * @param string $table     * @param string $colums     * @param string $ord     * @param string $sort     * @param string $limit     * @param string $sQid     * @return MySQL resource     */    function select($table, $colums=NULL, $ord=NULL, $sort = NULL, $limit = NULL, $sQid='')    {        if(!is_null($colums))        {            $query .= ' WHERE '.$colums;        }        $query .= ' ORDER BY '.$ord;        if(!is_null($sort))        {            $query .= ' '.$sort;        }        if(!is_null($limit))        {            $query .= ' LIMIT '. $limit;        }        $ret = @mysql_query('SELECT * FROM '.$table.$query) or $this->error();        $this->qnum++;        if(!empty($sQid))        {            $this->_setQueryID($sQid, $ret);        } else {            return $ret;        }    }    /**     * A short-hand version of the select function.     *     * @param string $table     * @param string $sQid     * @return MySQL Resource     */    function select_short($table, $sQid='')    {        $ret = @mysql_query('SELECT * FROM '.$table) or $this->error();        $this->qnum++;        if(!empty($sQid))        {            $this->_setQueryID($sQid, $ret);        } else {            return $ret;        }    }    /**     * Updates the MySQL table.     *     * @param string $table     * @param string $data     * @param string $where     * @return MySQL Resource     */    function update($table, $data, $where)    {        // Again, check our connection        if($this->connected !== true)        {            // Ohhhh, you gots an F!            $ret = false;            echo "You gotta connect before you can update anything bud!";        } else {            $ret = @mysql_query("UPDATE ".$table." SET ".$data." WHERE ".$where." LIMIT 1", $this->mdc) or $this->error();        }        $this->qnum++;        return $ret;    }    /**     * Deletes a row from the table     *     * @param string $table     * @param string $data     * @param int/string $limit     * @return MySQL Resource     */    function delete($table, $data, $limit="1")    {        // Again, check our connection        if($this->connected !== true)        {            // Ohhhh, you gots an F!            $ret = false;            echo "You gotta connect before you can delete anything bud!";        } else {            $ret = @mysql_query("DELETE FROM ".$table." WHERE ".$data." LIMIT ".$limit, $this->mdc) or $this-error();        }        $this->qnum++;        return $ret;    }    /**     * Run a custom MySQL query     *     * @param string $query     * @return MySQL Resource     */    function query($query)    {        if($this->connected !== true)        {            // Ohhhh, you gots an F!            $ret = false;            echo "You gotta connect before you can delete anything bud!";        } else {            $ret = @mysql_query($query, $this->mdc) or $this->error();        }        $this->qnum++;        return $ret;    }    /**     * Insert a row into a MySQL table.     *     * @param string $table     * @param array|string $cols     * @param array|string $vals     * @return MySQL Resource     */    function insert($table, $cols, $vals)    {        $ret = "INSERT INTO ".$table." ( ";        // check to see if the columns is an array or not..        if(is_array($cols))        {            // it is! so lets loop through them, and add them to the query            $t = count($cols);            $i = 0;            foreach($cols as $col)            {                $i++;                //checking to see if it's the last one in the array.                if($i !== $t)                {                    $ret .= "`".$col."` , ";                } else {                    $ret .= "`".$col."` ";                }            }        } else {            //it's not an arry.. so lets just slap it in there            $ret .= "`".$cols."`";        }        $ret .= " ) VALUES (";        //same thing as above, but with the insert values        if(is_array($vals))        {            $t = count($vals);            $i = 0;            foreach($vals as $val)            {                $i++;                if($i !== $t)                {                    $ret .= "'".$val."', ";                } else {                    $ret .= "'".$val."'";                }            }        } else {            $ret .= "'".$vals."'";        }        $ret .= ")";        $this->qnum++;        $ret = @mysql_query($ret) or $this->error();        return($ret);    }    /**     * Counts the rows in a table.     *     * @param string $table     * @param string $where     * @param int|string $limit     * @return row count integer     */    function rcount($table, $where=NULL, $limit=-1)    {        $query = "SELECT * FROM ".$table;        if(!is_null($where))        {            $query .= " WHERE ".$where;        }        if($limit > 0)        {            $query .= " LIMIT ".$limit;        }        $ret = @mysql_num_rows(mysql_query($query));        return($ret);    }    /**     * Sets the current query id.     *     * @access private     * @param integer $iQnum     * @param string $sQuery     */    function _setQueryID($iQnum, $sQuery)    {        $this->_qID[$iQnum] = $sQuery;    }    /**     * Returns an associative array of the data.     *     * @param resource|string $rQuery     * @param boolean $bNormQ     * @return Associative Array     */    function getAssoc($rQuery, $bNormQ=true)    {        if($bNormQ)        {            $ret = mysql_fetch_assoc($rQuery);        } else {            $ret = mysql_fetch_assoc($this->_qID[$rQuery]);        }        return $ret;    }    /**     * The error function     *     * @return boolean false     */    function error()    {        global $REMOTE_ADDR, $_SERVER;        $fp = fopen(SITE_PATH."logs/error.mysql.log", "a");        fwrite($fp, $REMOTE_ADDR." ERROR: ".mysql_error()."; URL: ".$_SERVER['REQUEST_URI']."\n");        mail("vouksh@vouksh.info", "MySQL Error", $REMOTE_ADDR." ERROR: ".mysql_error()."\n\nURL: ".$_SERVER['REQUEST_URI'], "FROM: [email]alerts@vouksh.info[/email]");        trigger_error("Uh oh, looks like we got an error in MySQL!<br />Logging this and emailing the admin<br />".mysql_error(), E_USER_ERROR);        return false;    }}?>
usage:
php Code:
    <?phpdefine('MYSQL_USER', 'myuser');define('MYSQL_PASS', 'mypass');$mysql = new mysql("myuser_mydb");// Select can be used to return a query or set it into a query id.$sel = $mysql->select("mytable", "a='b'", "id", "DESC", "5");// or$mysql->select("mytable", "a='b'", "id", "DESC", "5", 'selq1');// if we wanted to use the select statement using the query id...foreach($mysql->getAssoc('selq1', false) as $key => $val){//blah}// to insert..$mysql->insert("mytable", array('a','name','blah'), array('b', 'a name', 'bleh'));$mysql->close(); //wee we're done.?>

PHPDocumentor Generated Doc
So, you tell me, is this one better than the previous one?

Last edited by Vouksh; 03-16-2006 at 08:33 PM.
Reply With Quote


Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
installing red hat rich_m Unix/Linux/BSD 12 01-29-2006 10:25 AM
Mysql Library (class to make it easier) omanofmysteryp Share a PHP Script 6 11-11-2004 10:04 PM
MySQL ComCon Europe YoungCoder PHP Scripting 0 10-16-2004 08:31 AM
MySQL ComCon Europe YoungCoder PHP Scripting 0 09-26-2004 06:30 AM
MySQL ComCon Europe YoungCoder PHP Scripting 0 09-06-2004 05:43 AM