Location: PHPKode > scripts > Mysql DBObj > mysql-dbobj/Mysql.class.php
<?php
// Mysql connection class
// Made in 27/02/2004 by Vinícius Augusto Tagliatti Zani
// GPL License
//  <hide@address.com>

class Mysql {
    var $link;
    var $queryLink;
    var $host;
    var $username;
    var $password;
    var $query;
    var $where;
    var $limit;
    var $order;
    var $queryLink;
    var $table;
    var $database;
    var $finalQuery;
    var $error = array();
    
    /*  Constructor Mysql:
     *      opens a new mysql connection
     *      returns the connection link
     *  Example: $obj = new Mysql("localhost", "root", "");
     */
    function Mysql($host, $usr, $pwd) {
        $this->host = $host;
        $this->username = $usr;
        $this->password = $pwd;
        $this->link = @mysql_connect($this->host, $this->username, $this->password, true);
        return $this->link;
    }
    
    /*  Function assign:
     *      points an existing mysql connection link to the object link
     *      retorns itself
     *  Example: $obj->assign($my_link);
     */
    function assign($link) {
        $this->link = $link;
        return $this->link;
    }
    
    /*  Function selectDb:
     *      select the database for start using
     *      retorns the function result
     *  Example: $msql->selectDb("users");
     */
    function selectDb($db) {
        $this->database = $db;
        return @mysql_select_db($this->database, $this->link);
    }
    
    /*  Function query:
     *      adds the query to the object query and executes it (if $exec == true)
     *  Example:    $obj->whereAdd("usr_name = '".$obj->escape($name)."'");
     *              $obj->query("SELECT * FROM users", false);
     *              $obj->find();
     *      retorns the link to the executed query or TRUE, if the query wasn't executed
     */
    function query($query, $exec = true) {
        $this->query = $query;
        if ($exec) {
            return $this->find();
        } else {
            return true;
        }
    }
    
    /*  Function find:
     *      executes the query stored in the object
     *      retorns the query link
     *  Example: $obj->find();
     */
    function find() {
        $this->mountQuery();
        $this->queryLink = @mysql_query($this->finalQuery, $this->link);
        if ($this->queryLink == false) {
            $this->setError("Erro na query: ", true, true);
        }

        return $this->queryLink;
    }
    
    /*  Function mountQuery:
     *      mounts the query with the object avaliable data
     *      retorns the final query text
     *  Example: $obj->whereAdd("YEAR(data) = YEAR(NOW())");
     *           $str = $obj->mountQuery();
     */
    function mountQuery() {
        $this->finalQuery = $this->query . $this->where . $this->order . $this->limit;
        if ($this->finalQuery[sizeof($this->finalQuery)-1] != ";")
            $this->finalQuery .= ";";
            
        return $this->finalQuery;
    }
    
    /*  Function count:
     *      counts the number of rows affected by the last query
     *      retorns the number of affected rows
     *  Example: $num_res = $obj->count();
     */
    function count() {
        return @mysql_num_rows($this->queryLink);
    }
    
    /*  Function limit:
     *      limits the query's results ($query->limit(0, 10))
     *      or insertion, deletes ($query->limit(1))
     */
    function limit($start, $end = "") {
      if (!empty($this->query)) {
        if (ereg("limit", strtolower($this->query))) {
            $this->setError("Limit ja existente!");
            return false;
        }
      }
        if (!empty($end))
            $this->limit = " LIMIT ".$start.", ".$end;
        else
            $this->limit = " LIMIT ".$start;
        return true;
    }
    
    /*  Function whereAdd:
     *      adds a where clause to the object query
     *      multiples whereAdds are allowed
     */
    function whereAdd($condition) {
      if (!empty($this->where)) {
        if (ereg("where", strtolower($this->where)))
            $this->where .= " AND ( ".$condition.")";
        else
            $this->where = " WHERE ( ".$condition." )";
      } else {
            $this->where = " WHERE ( ".$condition." )";
      }
    }
    
    /*  Function orderBy:
     *      orders your query
     *      multiples orders are accepted
     */
    function orderBy($field) {
        $type = false;
        $search = array("ASC", "DESC");
        foreach ($search as $val) {
            if (ereg($val, strtoupper($field)))
                $type = true;
        }
        if (!empty($this->order)) {
            $this->order .= " AND ".$field.($type == true ? "" : " ASC");
        } else {
            $this->order .= " ORDER BY ".$field.($type == true ? "" : " ASC");
        }
        return true;
    }
    
    /*  Function fetch:
     *      returns an object of the actual query
     *  Example: $user = $query->fetch();
     */
    function fetch() {
        return @mysql_fetch_object($this->queryLink);
    }
    
    /*  Function fetchToThis:
     *      returns an object of the table INSIDE THIS object
     *  Example: $user->fetchToThis();
     *           echo $user->usr_nome;
     */
    function fetchToThis() {
        if ($tmp = mysql_fetch_assoc($this->queryLink)) {
            while (list($name, $val) = each($tmp)) {
                $this->{$name} = $val;
            }
            return $this;
        }
        return false;
    }
    
    /*  Function escape:
     *      escapes a string for use with mysql
     *      retorna the escaped string
     *  Example: $str = $mysql_obj->escape($str);
     */
    function escape($str) {
        $notAllowed = array("_", "<", ">");
        $replace = array("", "", "");
        $str = preg_replace($notAllowed, $replace, $str);
        if (function_exists('mysql_escape_string')) {
            return mysql_escape_string($str);
        } else {
            return addslashes($str);
        }
    }

    /*  Function setError:
     *      sets the mysql error
     *      if debug = true, the details of object are showed
     *      retorns true
     */
    function setError($err, $autoshow = true, $debug=false) {
        if (!$debug) {
            $this->error[] = "Error ".$err."<BR>" . mysql_error($this->link);
        } else {
            $this->error[] = "Erro : " .
                             $err ."<BR>" .
                             "Erro mysql: ".mysql_error($this->link)."<BR><BR>".
                             "Query atual: ".$this->finalQuery."<BR>".
                             "Database: ".$this->database."<BR>Tabela: ".$this->table."<BR>";
        }
        if ($autoshow)
            $this->showErrors();
    }
    
    /*  Function showErrors:
     *      show the erros ocourred with the object
     *      retorns true
     *  Example: $obj->showErrors(true);
     */
    function showErrors($die=false) {
        if (sizeof($this->error) > 0) {
            foreach ($this->error as $err) {
                echo $err."<BR><BR>";
            }
            if ($die)
                die;
        }
    }
}

?>
Return current item: Mysql DBObj