Home Backend Development PHP Tutorial [php]A MySQL database operation class written by myself_PHP tutorial

[php]A MySQL database operation class written by myself_PHP tutorial

Jul 20, 2016 am 11:12 AM
mysql php Write Function hand operate data database Compare of Simple kind Own

Practice by yourself and write a MySQL database operation class with relatively simple functions

<?php
/**
 * Created by JetBrains PhpStorm.
 * User:JAE
 * Date: 13-8-13
 * Time: 下午5:15
 * Blog:http://blog.jaekj.com
 * QQ:734708094
 * 通用数据库操作类
 * 版本:V1.1
 */

/* 数据库配置
  return array(
    &#39;DB_CONFIG&#39; => array(
        //数据库配置
        &#39;DB_HOST&#39;=>&#39;127.0.0.1&#39;,    //服务器地址
        &#39;DB_NAME&#39; => &#39;tmp&#39;, // 数据库名
        &#39;DB_USER&#39; => &#39;root&#39;, // 用户名
        &#39;DB_PWD&#39; => &#39;&#39;, // 密码
        &#39;DB_ENCODE&#39;=>&#39;utf8&#39;,//编码
        &#39;DB_PREFIX&#39; => &#39;dmtx_&#39; // 数据库表前缀
    )
);
 */
class M
{

    private $link; //数据库连接
    private $table; //表名
    private $prefix; //表前缀
    private $db_config; //数据库配置
    /**
     * 参数:表名 数据库配置数组 或 数据库配置文件路径
     * @param $table
     * @param string $db_config_arr_path
     */
    function __construct($table, $db_config_arr_path = &#39;config.php&#39;)
    {
        if (is_array($db_config_arr_path)) {
            $this->db_config = $db_config_arr_path;
        } else {
            $this->db_config = require($db_config_arr_path);
        }
        $this->conn();
        $this->table = $this->prefix . $table;
    }

    /**
     * 连接数据库
     */
    private function conn()
    {
        $db_config = $this->db_config;
        $host = $db_config["DB_CONFIG"]["DB_HOST"];
        $user = $db_config["DB_CONFIG"]["DB_USER"];
        $pwd = $db_config["DB_CONFIG"]["DB_PWD"];
        $db_name = $db_config["DB_CONFIG"]["DB_NAME"];
        $db_encode = $db_config["DB_CONFIG"]["DB_ENCODE"];
        $this->prefix = $db_config["DB_CONFIG"]["DB_PREFIX"];

        $this->link = mysql_connect($host, $user, $pwd) or die(&#39;数据库服务器连接错误:&#39; . mysql_error());
        mysql_select_db($db_name) or die(&#39;数据库连接错误:&#39; . mysql_error());
        mysql_query("set names &#39;$db_encode&#39;");
    }

    /**
     * 数据查询
     * 参数:sql条件 查询字段 使用的sql函数名
     * @param string $where
     * @param string $field
     * @param string $fun
     * @return array
     * 返回值:结果集 或 结果(出错返回空字符串)
     */
    public function select($where = &#39;1&#39;, $field = "*", $fun = &#39;&#39;)
    {
        $rarr = array();
        if (empty($fun)) {
            $sqlStr = "select $field from $this->table where $where";
            $rt = mysql_query($sqlStr, $this->link);
            while ($rt && $arr = mysql_fetch_assoc($rt)) {
                array_push($rarr, $arr);
            }
        } else {
            $sqlStr = "select $fun($field) as rt from $this->table where $where";
            $rt = mysql_query($sqlStr, $this->link);
            if ($rt) {
                $arr = mysql_fetch_assoc($rt);
                $rarr = $arr[&#39;rt&#39;];
            } else {
                $rarr = &#39;&#39;;
            }
        }
        return $rarr;
    }

    /**
     * 数据更新
     * 参数:sql条件 要更新的数据(字符串 或 关联数组)
     * @param $where
     * @param $data
     * @return bool
     * 返回值:语句执行成功或失败,执行成功并不意味着对数据库做出了影响
     */
    public function update($where, $data)
    {
        $ddata = &#39;&#39;;
        if (is_array($data)) {
            while (list($k, $v) = each($data)) {
                if (empty($ddata)) {
                    $ddata = "$k=&#39;$v&#39;";

                } else {
                    $ddata .= ",$k=&#39;$v&#39;";
                }
            }
        } else {
            $ddata = $data;
        }
        $sqlStr = "update $this->table set $ddata where $where";
        return mysql_query($sqlStr);
    }

    /**
     * 数据添加
     * 参数:数据(数组 或 关联数组 或 字符串)
     * @param $data
     * @return int
     * 返回值:插入的数据的ID 或者 0
     */
    public function insert($data)
    {
        $field = &#39;&#39;;
        $idata = &#39;&#39;;
        if (is_array($data) && array_keys($data) != range(0, count($data) - 1)) {
            //关联数组
            while (list($k, $v) = each($data)) {
                if (empty($field)) {
                    $field = "$k";
                    $idata = "&#39;$v&#39;";
                } else {
                    $field .= ",$k";
                    $idata .= ",&#39;$v&#39;";
                }
            }
            $sqlStr = "insert into $this->table($field) values ($idata)";
        } else {
            //非关联数组 或字符串
            if (is_array($data)) {
                while (list($k, $v) = each($data)) {
                    if (empty($idata)) {
                        $idata = "&#39;$v&#39;";
                    } else {
                        $idata .= ",&#39;$v&#39;";
                    }
                }

            } else {
                //为字符串
                $idata = $data;
            }
            $sqlStr = "insert into $this->table values ($idata)";
        }
        if(mysql_query($sqlStr,$this->link))
        {
            return mysql_insert_id($this->link);
        }
        return 0;
    }

    /**
     * 数据删除
     * 参数:sql条件
     * @param $where
     * @return bool
     */
    public function delete($where)
    {
        $sqlStr = "delete from $this->table where $where";
        return mysql_query($sqlStr);
    }

    /**
     * 关闭MySQL连接
     * @return bool
     */
    public function close()
    {
        return mysql_close($this->link);
    }

}


//$hj = new M("user");
//echo $hj->insert("NULL,&#39;hj.q@qq.com&#39;,&#39;cde&#39;");
//$arr = $hj->select();
//print_r($arr);
//echo $hj->update("id>3",array("email"=>"bn@c.cc"));
Copy after login



[php]A MySQL database operation class written by myself_PHP tutorial

<?php

require &#39;Query/M.class.php&#39;;

$hj = new M("user");
//增
echo $hj->insert(array("NULL","1@qq.com","xxx"));
echo $hj->insert(array("email"=>"12@qq.com","password"=>"cccc"));
echo $hj->insert("NULL,&#39;123@qq.com&#39;,&#39;cde&#39;");

//查
//查看所有数据
$arr = $hj->select();
print_r($arr);
//查看id大于3且id小于6 的id 和email 字段 的所有数据
$arr = $hj->select("id>3 and id<6","id,email");
print_r($arr);
//获取数据库中一共有多少条记录
$rt = $hj->select("1","*","count");
echo $rt;

// 改
$b = $hj->update("id=1","email = &#39;1234@qq.com&#39;");
echo $b;
$b = $hj->update("id>3 and id<6",array("email"=>"1234@qq.com"));
echo $b;

// 删
$b = $hj->delete("id>3");
echo $b;

//关闭
$hj->close();
Copy after login



www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444556.htmlTechArticlePractice yourself and write a MySQL database operation class with relatively simple functions?php/** * Created by JetBrains PhpStorm. * User:JAE * Date: 13-8-13 * Time: 5:15 pm * Blog:http://bl...
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's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

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.

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

See all articles