Home Backend Development PHP Tutorial php mysql数据库操作类_php实例

php mysql数据库操作类_php实例

Jun 07, 2016 pm 05:26 PM
mysql php database

复制代码 代码如下:

/*
 *    mysql数据库 DB类
 *    @package    db
 *    @author        yytcpt(无影)
 *    @version    2008-03-27
 *    @copyrigth    http://www.d5s.cn/ 
 */
class db {
    var $connection_id = "";
    var $pconnect = 0;
    var $shutdown_queries = array();
    var $queries = array();
    var $query_id = "";
    var $query_count = 0;
    var $record_row = array();
    var $failed = 0;
    var $halt = "";
    var $query_log = array();
    function connect($db_config){
        if ($this->pconnect){
            $this->connection_id = mysql_pconnect($db_config["hostname"], $db_config["username"], $db_config["password"]);
        }else{
            $this->connection_id = mysql_connect($db_config["hostname"], $db_config["username"], $db_config["password"]);
        }
        if ( ! $this->connection_id ){
            $this->halt("Can not connect MySQL Server");
        }
        if ( ! @mysql_select_db($db_config["database"], $this->connection_id) ){
            $this->halt("Can not connect MySQL Database");
        }
        if ($db_config["charset"]) {
            @mysql_unbuffered_query("SET NAMES '".$db_config["charset"]."'");
        }
        return true;
    }
    //发送SQL 查询,并返回结果集
    function query($query_id, $query_type='mysql_query'){
        $this->query_id = $query_type($query_id, $this->connection_id);
        $this->queries[] = $query_id;
        if (! $this->query_id ) {
            $this->halt("查询失败:\n$query_id");
        }
        $this->query_count++;
        $this->query_log[] = $str;
        return $this->query_id;
    }
    //发送SQL 查询,并不获取和缓存结果的行
    function query_unbuffered($sql=""){
        return $this->query($sql, 'mysql_unbuffered_query');
    }
    //从结果集中取得一行作为关联数组
    function fetch_array($sql = ""){
        if ($sql == "") $sql = $this->query_id;
        $this->record_row = @mysql_fetch_array($sql, MYSQL_ASSOC);
        return $this->record_row;
    }
    function shutdown_query($query_id = ""){
        $this->shutdown_queries[] = $query_id;
    }
    //取得结果集中行的数目,仅对 INSERT,UPDATE 或者 DELETE
    function affected_rows() {
        return @mysql_affected_rows($this->connection_id);
    }
    //取得结果集中行的数目,仅对 SELECT 语句有效
    function num_rows($query_id="") {
        if ($query_id == "") $query_id = $this->query_id;
        return @mysql_num_rows($query_id);
    }
    //返回上一个 MySQL 操作中的错误信息的数字编码
    function get_errno(){
        $this->errno = @mysql_errno($this->connection_id);
        return $this->errno;
    }
    //取得上一步 INSERT 操作产生的 ID
    function insert_id(){
        return @mysql_insert_id($this->connection_id);
    }
    //得到查询次数
    function query_count() {
        return $this->query_count;
    }
    //释放结果内存
    function free_result($query_id=""){
           if ($query_id == "") $query_id = $this->query_id;
        @mysql_free_result($query_id);
    }
    //关闭 MySQL 连接
    function close_db(){
        if ( $this->connection_id ) return @mysql_close( $this->connection_id );
    }
    //列出 MySQL 数据库中的表
    function get_table_names(){
        global $db_config;
        $result = mysql_list_tables($db_config["database"]);
        $num_tables = @mysql_numrows($result);
        for ($i = 0; $i             $tables[] = mysql_tablename($result, $i);
        }
        mysql_free_result($result);
        return $tables;
       }
    //从结果集中取得列信息并作为对象返回,取得所有字段
    function get_result_fields($query_id=""){
           if ($query_id == "") $query_id = $this->query_id;
        while ($field = mysql_fetch_field($query_id)) {
            $fields[] = $field;
        }
        return $fields;
       }
    //错误提示
    function halt($the_error=""){
        $message = $the_error."
\r\n";
        $message.= $this->get_errno() . "
\r\n";
        $sql = "INSERT INTO `db_error`(pagename, errstr, timer) VALUES('".$_SERVER["PHP_SELF"]."', '".addslashes($message)."', ".time().")";
        @mysql_unbuffered_query($sql);
        if (DEBUG==true){
            echo "MySQL 数据库错误";
            echo "\r\n";
            echo "\r\n";
            echo "
\r\n";
            echo "\r\n";
            echo "
\r\n";
            exit;
        }
    }
    function __destruct(){
        $this->shutdown_queries = array();
        $this->close_db();
    }
    function sql_select($tbname, $where="", $limit=0, $fields="*", $orderby="id", $sort="DESC"){
        $sql = "SELECT ".$fields." FROM `".$tbname."` ".($where?" WHERE ".$where:"")." ORDER BY ".$orderby." ".$sort.($limit ? " limit ".$limit:"");
        return $sql;
    }
    function sql_insert($tbname, $row){
        foreach ($row as $key=>$value) {
            $sqlfield .= $key.",";
            $sqlvalue .= "'".$value."',";
        }
        return "INSERT INTO `".$tbname."`(".substr($sqlfield, 0, -1).") VALUES (".substr($sqlvalue, 0, -1).")";
    }
    function sql_update($tbname, $row, $where){
        foreach ($row as $key=>$value) {
            $sqlud .= $key."= '".$value."',";
        }
        return "UPDATE `".$tbname."` SET ".substr($sqlud, 0, -1)." WHERE ".$where;
    }
    function sql_delete($tbname, $where){
        return "DELETE FROM `".$tbname."` WHERE ".$where;
    }
    //新增加一条记录
    function row_insert($tbname, $row){
        $sql = $this->sql_insert($tbname, $row);
        return $this->query_unbuffered($sql);
    }
    //更新指定记录
    function row_update($tbname, $row, $where){
        $sql = $this->sql_update($tbname, $row, $where);
        return $this->query_unbuffered($sql);
    }
    //删除满足条件的记录
    function row_delete($tbname, $where){
        $sql = $this->sql_delete($tbname, $where);
        return $this->query_unbuffered($sql);
    }
    /*    根据条件查询,返回所有记录
     *    $tbname 表名, $where 查询条件, $limit 返回记录, $fields 返回字段
     */
    function row_select($tbname, $where="", $limit=0, $fields="*", $orderby="id", $sort="DESC"){
        $sql = $this->sql_select($tbname, $where, $limit, $fields, $orderby, $sort);
        return $this->row_query($sql);
    }
    //详细显示一条记录
    function row_select_one($tbname, $where, $fields="*", $orderby="id"){
        $sql = $this->sql_select($tbname, $where, 1, $fields, $orderby);
        return $this->row_query_one($sql);
    }
    function row_query($sql){
        $rs     = $this->query($sql);
        $rs_num = $this->num_rows($rs);
        $rows = array();
        for($i=0; $i            $rows[] = $this->fetch_array($rs);
        }
        $this->free_result($rs);
        return $rows;
    }
    function row_query_one($sql){
        $rs     = $this->query($sql);
        $row = $this->fetch_array($rs);
        $this->free_result($rs);
        return $row;
    }
    //计数统计
    function row_count($tbname, $where=""){
        $sql = "SELECT count(id) as row_sum FROM `".$tbname."` ".($where?" WHERE ".$where:"");
        $row = $this->row_query_one($sql);
        return $row["row_sum"];
    }
}
?>

很久没有发帖了,把我常用的一些php类文件分享出来。
如果您加了新功能,或者是有改进,请与大家一起分享。
复制代码 代码如下:

    $db_config["hostname"]    = "127.0.0.1";    //服务器地址
    $db_config["username"]    = "root";        //数据库用户名
    $db_config["password"]    = "root";        //数据库密码
    $db_config["database"]    = "wap_blueidea_com";        //数据库名称
    $db_config["charset"]        = "utf8";
    include('db.php');
    $db    = new db();
    $db->connect($db_config);
    //例:查询表 table_name 中 cid=1的所有记录。
    $row = $db->row_select('table_name', 'cid=1');
?>

更详细的使用方法,请参考 db类文件中的注释。 
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 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)

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.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

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.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles