《PHP操作数据库mysql的类 完成增、删、改、查操作》

<?php

/**
 * 操作数据库mysql 的类,完成增删改查的操作
 *
 */
class ms_new_mysql {

    private $dbHost;
    private $dbUser;
    private $dbPassword;
    private $dbTable;
    private $dbConn;
    private $result;
    private $sql;
    private $pre;
    private $coding;
    private $pcon;
    private $queryNum;
    private static $daoImpl;

    public function __construct($dbHost, $dbUser, $dbPassword, $dbTable, $pre, $coding, $pcon) {
        $this->dbHost = $dbHost;
        $this->dbUser = $dbUser;
        $this->dbPassword = $dbPassword;
        $this->dbTable = $dbTable;
        $this->pre = $pre;
        $this->coding = $coding;
        $this->pcon = $pcon;
        $this->connect();
        $this->select_db($dbTable);
    }

    public function __clone() {
        return self::$daoImpl;
    }

    public static function getDaoImpl($linkConfig) {

        if (empty(self::$daoImpl)) {
            self::$daoImpl = new ms_new_mysql($linkConfig['db']['dbhost'], $linkConfig['db']['dbuser'], $linkConfig['db']['dbpw'], $linkConfig['db']['dbname'], $linkConfig['db']['tablepre'], $linkConfig['db']['dbcharset'], $linkConfig['db']['pconnect']);
        }
        return self::$daoImpl;
    }

    public function connect() {
        $func = $this->pcon == 1 ? "mysql_pconnect" : "mysql_connect";

        //$this->dbConn = @$func($this->dbHost, $this->dbUser, $this->dbPassword);
        $this->dbConn = mysql_connect($this->dbHost, $this->dbUser, $this->dbPassword, $this->pcon);
        if (!$this->dbConn) {
            $this->halt("不能链接数据库", $this->sql);
            return false;
        }
        if ($this->version() > '4.1') {
            $serverset = $this->coding ? "character_set_connection='$this->coding',character_set_results='$this->coding',character_set_client=binary" : '';
            $serverset .= $this->version() > '5.0.1' ? ((empty($serverset) ? '' : ',') . " sql_mode='' ") : '';
            $serverset && mysql_query("SET $serverset", $this->dbConn);
        }
        return $this->dbConn;
    }

    /**
     * 选择一个数据库
     *
     * @param string $dbTable
     * @return boolean
     */
    public function select_db($dbTable) {
        if (!@mysql_select_db($dbTable, $this->dbConn)) {
            $this->halt("没有" . $dbTable . "这个数据库");
            return false;
        } else {
            $this->dbTable = $dbTable;
            return true;
        }
    }

    /**
     * 查询语句,传过来一个sql,执行,如果语句正确,返回结果集资源
     *
     * @param string $sql
     * @param string $type
     * @return Resouce query
     */
    public function query($sql, $type = '') {

        if ($query = mysql_query($sql, $this->dbConn)) {
            $this->queryNum++;
            return $query;
        } else {
            $this->halt("Mysql 查询出错", $sql);
            return false;
        }
    }

    /**
     * 插入一组数据或一条数据
     *
     * @param string $tableName
     * @param boolean
     */
    public function insert($tableName, $info) {

        $this->checkFields($tableName, $info);
        $insert_sql = "INSERT INTO `$tableName`(`" . implode('`,`', array_keys($info)) . "`) VALUES('" . implode("','", $info) . "')";
        return $this->query("$insert_sql");
    }

    /**
     * 更细数据库中的数据
     *
     * @param string $tableName
     * @param array $info
     * @param string $where
     * @return boolean
     */
    public function update($tableName, $info, $where = '') {
        $this->checkFields($tableName, $info);
        if ($where) {
            $sql = '';

            foreach ($info as $k => $v) {
                $sql .= ", `$k`='$v'";
            }
            $sql = substr($sql, 1);

            $sql = "UPDATE `$tableName` SET $sql WHERE $where";
        } else {
            $sql = "REPLACE INTO `$tableName`(`" . implode('`,`', array_keys($info)) . "`) VALUES('" . implode("','", $info) . "')";
        }
        return $this->query($sql);
    }

    /**
     * 检查一个字段是否在这张表中存在
     *
     * @param string $tableName
     * @param array $array
     * @return message
     */
    public function checkFields($tableName, $array) {

        $fields = $this->getFields($tableName);

        foreach ($array as $key => $val) {
            if (!in_array($key, $fields)) {
                $this->halt("Mysql 错误", "找不到" . $key . "这个字段在" . $tableName . "里面");
                return false;
            }
        }
    }

    /**
     * 获取一张表中的所有字段
     *
     * @param string $tableName
     * @return array fileds
     */
    public function getFields($tableName) {
        $fields = array();
        $result = $this->query("SHOW COLUMNS FROM `$tableName`");
        while ($list = $this->fetchArray($result)) {
            $fields[] = $list['Field'];
        }
        $this->freeResult($result);
        return $fields;
    }

    /**
     * 释放当前数据库结果集的内存
     *
     * @param Resource $result
     * @return null
     */
    public function freeResult($result) {
        return @mysql_free_result($result);
    }

    /**
     * 使用while 可以迭代输出 一个结果集中的所有数据
     *
     * @param Resouce $query
     * @param result type $result_type
     * @return array
     */
    public function fetchArray($query, $result_type = MYSQL_ASSOC) {
        return mysql_fetch_array($query, $result_type);
    }

    /**
     * 返回一个结果集中的一条数据
     *
     * @param $sql $query
     * @param string $type
     * 
     * 
     */
    public function getOne($sql, $type = '', $expires = 3600) {
        $query = $this->query($sql, $type, $expires);
        $rs = $this->fetchArray($query);
        $this->freeResult($rs);
        return $rs;
    }

    /**
     * 获取插入的数据的返回的insetid
     *
     * @return insetid
     */
    public function insertId() {
        return mysql_insert_id($this->dbConn);
    }

    /**
     * 获取当前的结果集中存在多少条数据
     *
     * @param string $query
     * @return int nums
     */
    public function numRows($query) {
        return @mysql_numrows($query);
    }

    /**
     * 获取当前的结果集中,有多少个字段
     *
     * @param Resouce $query
     * @return int fields nums
     */
    public function numFields($query) {
        return @mysql_num_fields($query);
    }

    /**
     * 获取当前执行的sql总条数
     *
     * @return queryNum
     */
    public function getQueryNum() {
        return $this->queryNum;
    }

    /**
     * 获取当前文件中的函数,传入一个当前类存在函数,单例调用
     *
     * @param unknown_type $funcname
     * @param unknown_type $params
     * @return unknown
     */
    public function getFunc($funcname, $params = '') {
        if (empty($params)) {
            return $this->$funcname();
        } else {
            return $this->$funcname($this->getFuncParams($params));
        }
    }

    /**
     * 如果是一个数组,那么拼接起来,处理返回一个参数集合
     *
     * @param array,string $params
     * @return string a,d,3
     */
    public function getFuncParams($params) {
        $returnStr = "";
        if (is_array($params)) {
            foreach ($params as $key => $val) {
                $returnStr .= $val . ",";
            }
            return rtrim($returnStr, ",");
        } else {
            return $params;
        }
    }

    /**
     * 获取当前数据库的版本信息
     *
     * @return version
     */
    public function version() {
        return mysql_get_server_info($this->dbConn);
    }

    /**
     * 获取当前mysql数据的报错号
     *
     * @return errorno
     */
    public function errno() {
        return intval(@mysql_errno($this->dbConn));
    }

    /**
     * 获取当前数据库的 提示信息
     *
     * @return unknown
     */
    public function error() {
        return @mysql_error($this->dbConn);
    }

    /**
     * 操作数据库出错,提示信息
     *
     * @param unknown_type $message
     * @param unknown_type $sql
     */
    function halt($message = '', $sql = '') {
        $this->errormsg = "<b>MySQL Query : </b>$sql <br /><b> MySQL Error : </b>" . $this->error() . " <br /> <b>MySQL Errno : </b>" . $this->errno() . " <br /><b> Message : </b> $message";
        exit($this->errormsg);
    }

    function showTable() {
        $tables = array();
        $result = $this->query("SHOW TABLES");
        while ($list = $this->fetchArray($result)) {
            $tables[] = $list['Tables_in_' . $this->dbTable];
        }
        $this->freeResult($result);
        return $tables;
    }

}

$dbObj = new ms_new_mysql("127.0.0.1", "root", "", "", "", "utf-8", "0");

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 PHP 操作 MySQL 数据库的示例代码,实现的功能: 连接数据库: ```php <?php $host = 'localhost'; // 数据库主机名 $user = 'root'; // 数据库用户名 $password = 'password'; // 数据库密码 $database = 'test'; // 数据库名 // 创建连接 $conn = mysqli_connect($host, $user, $password, $database); // 检测连接是否成功 if (!$conn) { die("连接失败: " . mysqli_connect_error()); } echo "连接成功"; ?> ``` 插入数据: ```php <?php $sql = "INSERT INTO users (name, email, age) VALUES ('John Doe', 'john@example.com', '30')"; if (mysqli_query($conn, $sql)) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 关闭连接 mysqli_close($conn); ?> ``` 更新数据: ```php <?php $sql = "UPDATE users SET age='40' WHERE id=1"; if (mysqli_query($conn, $sql)) { echo "记录更新成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 关闭连接 mysqli_close($conn); ?> ``` 询数据: ```php <?php $sql = "SELECT id, name, email, age FROM users"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // 输出数据 while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. " - Age: " . $row["age"]. "<br>"; } } else { echo "0 条结果"; } // 关闭连接 mysqli_close($conn); ?> ``` 除数据: ```php <?php $sql = "DELETE FROM users WHERE id=1"; if (mysqli_query($conn, $sql)) { echo "记录除成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 关闭连接 mysqli_close($conn); ?> ``` 以上代码仅供参考,具体实现还需根据实际情况进行调整。同时,为了避免 SQL 注入等安全问题,请务必进行数据过滤和转义。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值