Table of Contents
php代码    
Home php教程 PHP源码 数据库操作类

数据库操作类

May 25, 2016 pm 05:14 PM
php

php代码    

<?php 
/*
 * 数据库操作类
 * 
 */


class Mysql { 
    private $server = ""; 
    private $user = ""; 
    private $password = ""; 
    private $database = ""; 
    private $linkMode = 1; 
    private $link_id = 0; 
    private $query_id = 0; 
    private $query_times = 0; 
    private $result = array (); 
    private $fetchMode = MYSQL_ASSOC; 
    private $err_no = 0; 
    private $err_msg; 
    private $character; 
    //====================================== 
    // 函数: mysql() 
    // 功能: 构造函数 
    // 参数: 参数类的变量定义 
    // 说明: 构造函数将自动连接数据库 
    // 如果想手动连接去掉自动连接函数 
    //====================================== 
    public function __construct($server, $user, $password, $database, $character = "UTF8", $linkMode = 0) { 
        if (empty ( $server ) || empty ( $user ) || empty ( $database )) 
            $this->halt ( "提交的数据库信息不完整!请检查服务器地址,用户和数据库是否正确有效" ); 
         
        $this->server = $server; 
        $this->user = $user; 
        $this->password = $password; 
        $this->database = $database; 
        $this->linkMode = $linkMode; 
        $this->character = $character; 
        $this->connect (); 
    } 
    //====================================== 
    // 函数: connect($server,$user,$password,$database) 
    // 功能: 连接数据库 
    // 参数: $server 主机名, $user 用户名 
    // 参数: $password 密码, $database 数据库名称 
    // 返回: 0:失败 
    // 说明: 默认使用类中变量的初始值 
    //====================================== 
    public function connect($server = "", $user = "", $password = "", $database = "") { 
        $server = $server ? $server : $this->server; 
        $user = $user ? $user : $this->user; 
        $password = $password ? $password : $this->password; 
        $database = $database ? $database : $this->database; 
         
        $this->link_id = $this->linkMode ? mysql_pconnect ( $server, $user, $password, $database ) : mysql_connect ( $server, $user, $password, $database ); 
         
        if (! $this->link_id) { 
            $this->halt ( "数据库连接失败!请检查各项参数!" ); 
            return 0; 
        } 
         
        if (! mysql_select_db ( $database, $this->link_id )) { 
            $this->halt ( "无法选择数据库" ); 
            return 0; 
        } 
         
        if ($this->character != "GBK" && $this->character != "UTF8") { 
            $this->halt ( "输入的编码模式不正确!" ); 
            return 0; 
        } 
         
        $this->query ( &#39;SET NAMES &#39; . $this->character ); 
        return $this->link_id; 
    } 
    //====================================== 
    // 函数: query($sql) 
    // 功能: 数据查询 
    // 参数: $sql 要查询的SQL语句 
    // 返回: 0:失败 
    //====================================== 
    public function query($sql) { 
        $this->query_times ++; 
        $this->query_id = mysql_query ( $sql, $this->link_id ); 
        if (! $this->query_id) { 
            $this->halt ( "<font color=red>" . $sql . "</font> 语句执行不成功!" ); 
            return 0; 
        } 
         
        return $this->query_id; 
    } 
    //====================================== 
    // 函数: setFetchMode($mode) 
    // 功能: 设置取得记录的模式 
    // 参数: $mode 模式 MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH 
    // 返回: 0:失败 
    //====================================== 
    public function setFetchMode($mode) { 
        if ($mode == MYSQL_ASSOC || $mode == MYSQL_NUM || $mode == MYSQL_BOTH) { 
            $this->fetchMode = $mode; 
            return 1; 
        } else { 
            $this->halt ( "错误的模式." ); 
            return 0; 
        } 
    } 
    //====================================== 
    // 函数: fetchRow() 
    // 功能: 从记录集中取出一条记录 
    // 返回: 0: 出错 record: 一条记录 
    //====================================== 
    public function fetchRow() { 
        $this->record = mysql_fetch_array ( $this->query_id, $this->fetchMode ); 
         
        return $this->record; 
    } 
    //====================================== 
    // 函数: fetchAll() 
    // 功能: 从记录集中取出所有记录 
    // 返回: 记录集数组 
    //====================================== 
    public function fetchAll() { 
        $arr [] = array (); 
         
        while ( $this->record = mysql_fetch_array ( $this->query_id, $this->fetchMode ) ) 
            $arr [] = $this->record; 
         
        mysql_free_result ( $this->query_id ); 
        return $arr; 
    } 
    //====================================== 
    // 函数: getValue() 
    // 功能: 返回记录中指定字段的数据 
    // 参数: $field 字段名或字段索引 
    // 返回: 指定字段的值 
    //====================================== 
    public function getValue($filed) { 
        return $this->record [$filed]; 
    } 
    //====================================== 
    // 函数: getquery_id() 
    // 功能: 返回查询号 
    //======================================     
    public function getquery_id() { 
        return $this->query_id; 
    } 
    //====================================== 
    // 函数: affectedRows() 
    // 功能: 返回影响的记录数 
    //======================================     
    public function affectedRows() { 
        return mysql_affected_rows ( $this->link_id ); 
    } 
    //====================================== 
    // 函数: recordCount() 
    // 功能: 返回查询记录的总数 
    // 参数: 无 
    // 返回: 记录总数 
    //======================================     
    public function recordCount() { 
        return mysql_num_rows ( $this->query_id ); 
    } 
    //====================================== 
    // 函数: getquery_times() 
    // 功能: 返回查询的次数 
    // 参数: 无 
    // 返回: 查询的次数 
    //======================================     
    public function getquery_times() { 
        return $this->query_times; 
    } 
    //====================================== 
    // 函数: getVersion() 
    // 功能: 返回mysql的版本 
    // 参数: 无 
    //======================================     
    public function getVersion() { 
        $this->query ( "select version() as ver" ); 
        $this->fetchRow (); 
        return $this->getValue ( "ver" ); 
    } 
    //====================================== 
    // 函数: getDBSize($database, $tblPrefix=null) 
    // 功能: 返回数据库占用空间大小 
    // 参数: $database 数据库名 
    // 参数: $tblPrefix 表的前缀,可选 
    //======================================     
    public function getDBSize($database, $tblPrefix = null) { 
        $sql = "SHOW TABLE STATUS FROM " . $database; 
        if ($tblPrefix != null) { 
            $sql .= " LIKE &#39;$tblPrefix%&#39;"; 
        } 
        $this->query ( $sql ); 
        $size = 0; 
        while ( $this->fetchRow () ) 
            $size += $this->getValue ( "Data_length" ) + $this->getValue ( "Index_length" ); 
        return $size; 
    } 
    //====================================== 
    // 函数: halt($err_msg) 
    // 功能: 处理所有出错信息 
    // 参数: $err_msg 自定义的出错信息 
    //=====================================     
    public function halt($err_msg = "") { 
        if ($err_msg == "") { 
            $this->errno = mysql_errno (); 
            $this->error = mysql_error (); 
            echo "<b>mysql error:<b><br>"; 
            echo $this->errno . ":" . $this->error . "<br>"; 
            exit (); 
        } else { 
            echo "<b>mysql error:<b><br>"; 
            echo $err_msg . "<br>"; 
            exit (); 
        } 
    } 
    //====================================== 
    // 函数: insertID() 
    // 功能: 返回最后一次插入的自增ID 
    // 参数: 无 
    //======================================     
    public function insertID() { 
        return mysql_insert_id (); 
    } 
    //====================================== 
    //函数:close() 
    //功能:关闭非永久的数据库连接 
    //参数:无 
    //====================================== 
    public function close() { 
        $link_id = $link_id ? $link_id : $this->link_id; 
        mysql_close ( $link_id ); 
    } 
    //====================================== 
    // 函数: sqlSelect() 
    // 功能: 返回组合的select查询值 
    // 参数: $tbname 查询的表名 
    // 参数: $where 条件 
    // 参数: $fields 字段值 
    // 参数: $orderby 按某字段排序 
    // 参数: $sort 正序ASC,倒序DESC,$orderby 不为空是有效 
    // 参数: $limit 取得记录的条数,0,8 
    // 返回: 查询语句 
    //====================================== 
    function sqlSelect($tbname, $where = "", $limit = 0, $fields = "*", $orderby = "", $sort = "DESC") { 
        $sql = "SELECT " . $fields . " FROM " . $tbname . ($where ? " WHERE " . $where : "") . ($orderby ? " ORDER BY " . $orderby . " " . $sort : "") . ($limit ? " limit " . $limit : ""); 
        return $sql; 
    } 
    //====================================== 
    // 函数: sqlInsert() 
    // 功能: Insert插入数据函数 
    // 参数: $taname 要插入数据的表名 
    // 参数: $row 要插入的内容 (数组) 
    // 返回: 记录总数 
    // 返回: 插入语句 
    //====================================== 
    function sqlInsert($tbname, $row) { 
        foreach ( $row as $key => $value ) { 
            $sqlfield .= $key . ","; 
            $sqlvalue .= "&#39;" . $value . "&#39;,"; 
        } 
        return "INSERT INTO " . $tbname . "(" . substr ( $sqlfield, 0, - 1 ) . ") VALUES (" . substr ( $sqlvalue, 0, - 1 ) . ")"; 
    } 
    //====================================== 
    // 函数: sqlUpdate() 
    // 功能: Update更新数据的函数 
    // 参数: $taname 要插入数据的表名 
    // 参数: $row 要插入的内容 (数组) 
    // 参数: $where 要插入的内容 的条件 
    // 返回: Update语句 
    //======================================     
    function sqlUpdate($tbname, $row, $where) { 
        foreach ( $row as $key => $value ) { 
            $sqlud .= $key . "= &#39;" . $value . "&#39;,"; 
        } 
        return "UPDATE " . $tbname . " SET " . substr ( $sqlud, 0, - 1 ) . " WHERE " . $where; 
    } 
    //====================================== 
    // 函数: sqlDelete() 
    // 功能: 删除指定条件的行 
    // 参数: $taname 要插入数据的表名 
    // 参数: $where 要插入的内容 的条件 
    // 返回: DELETE语句 
    //======================================     
    function sqlDelete($tbname, $where) { 
        if (! $where) { 
            $this->halt ( "删除函数没有指定条件!" ); 
            return 0; 
        } 
        return "DELETE FROM " . $tbname . " WHERE " . $where; 
    } 
     
    //====================================== 
    //函数:checkSql SQL语句的过滤 
    //功能:过滤一些特殊语法 
    //参数:$db_string 查询的SQL语句 
    //参数:$querytype 查询的类型 
    //====================================== 
    function checkSql($db_string, $querytype = &#39;select&#39;) { 
        $clean = &#39;&#39;; 
        $old_pos = 0; 
        $pos = - 1; 
         
        //如果是普通查询语句,直接过滤一些特殊语法 
        if ($querytype == &#39;select&#39;) { 
            $notallow1 = "[^0-9a-z@\._-]{1,}(union|sleep|benchmark|load_file|outfile)[^0-9a-z@\.-]{1,}"; 
             
            //$notallow2 = "--|/\*"; 
            if (eregi ( $notallow1, $db_string )) { 
                exit ( "<font size=&#39;5&#39; color=&#39;red&#39;>Safe Alert: Request Error step 1 !</font>" ); 
            } 
        } 
         
        //完整的SQL检查 
        while ( true ) { 
            $pos = strpos ( $db_string, &#39;\&#39;&#39;, $pos + 1 ); 
            if ($pos === false) { 
                break; 
            } 
            $clean .= substr ( $db_string, $old_pos, $pos - $old_pos ); 
            while ( true ) { 
                $pos1 = strpos ( $db_string, &#39;\&#39;&#39;, $pos + 1 ); 
                $pos2 = strpos ( $db_string, &#39;\\&#39;, $pos + 1 ); 
                if ($pos1 === false) { 
                    break; 
                } elseif ($pos2 == false || $pos2 > $pos1) { 
                    $pos = $pos1; 
                    break; 
                } 
                $pos = $pos2 + 1; 
            } 
            $clean .= &#39;$s$&#39;; 
            $old_pos = $pos + 1; 
        } 
        $clean .= substr ( $db_string, $old_pos ); 
        $clean = trim ( strtolower ( preg_replace ( array (&#39;~\s+~s&#39; ), array (&#39; &#39; ), $clean ) ) ); 
         
        //老版本的Mysql并不支持union,常用的程序里也不使用union,但是一些黑客使用它,所以检查它 
        if (strpos ( $clean, &#39;union&#39; ) !== false && preg_match ( &#39;~(^|[^a-z])union($|[^[a-z])~s&#39;, $clean ) != 0) { 
            $fail = true; 
        } 

        //发布版本的程序可能比较少包括--,#这样的注释,但是黑客经常使用它们 
        elseif (strpos ( $clean, &#39;/*&#39; ) > 2 || strpos ( $clean, &#39;--&#39; ) !== false || strpos ( $clean, &#39;#&#39; ) !== false) { 
            $fail = true; 
        } 

        //这些函数不会被使用,但是黑客会用它来操作文件,down掉数据库 
        elseif (strpos ( $clean, &#39;sleep&#39; ) !== false && preg_match ( &#39;~(^|[^a-z])sleep($|[^[a-z])~s&#39;, $clean ) != 0) { 
            $fail = true; 
        } elseif (strpos ( $clean, &#39;benchmark&#39; ) !== false && preg_match ( &#39;~(^|[^a-z])benchmark($|[^[a-z])~s&#39;, $clean ) != 0) { 
            $fail = true; 
        } elseif (strpos ( $clean, &#39;load_file&#39; ) !== false && preg_match ( &#39;~(^|[^a-z])load_file($|[^[a-z])~s&#39;, $clean ) != 0) { 
            $fail = true; 
        } elseif (strpos ( $clean, &#39;into outfile&#39; ) !== false && preg_match ( &#39;~(^|[^a-z])into\s+outfile($|[^[a-z])~s&#39;, $clean ) != 0) { 
            $fail = true; 
        } 

        //老版本的MYSQL不支持子查询,我们的程序里可能也用得少,但是黑客可以使用它来查询数据库敏感信息 
        elseif (preg_match ( &#39;~\([^)]*?select~s&#39;, $clean ) != 0) { 
            $fail = true; 
        } 
        if (! empty ( $fail )) { 
            exit ( "<font size=&#39;5&#39; color=&#39;red&#39;>Safe Alert: Request Error step 2!</font>" ); 
        } else { 
            return $db_string; 
        } 
    } 
    //====================================== 
    //函数:析构函数 
    //功能:释放类,关闭非永久的数据库连接 
    //参数:无 
    //====================================== 
    public function __destruct() { 
        $this->close (); 
    } 
} 
?>
Copy after login

                   

                   

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles