封装PDO函数

funPDO.php

<?php

/**
 * @title: 封装PDO函数
 * 
 * @Features:
 *  1. 封装 SELECT ,INSERT,DELETE,UPDATE 操作 @done(2019-3-22 13:35:30)
 *  2. 加入回滚事务 @done(2019-3-22 15:35:46)
 * 
 * @ TODO:
 *  1. 完善SQL语句的漏洞屏蔽
 *  2. 学习面向对象后,封装成类
 *  3. 继续补充PDO知识,完善此函数
 * 
 *
 * @author Paul <19805123@qq.com>
 * @version 0.1
 * @created 2019-3-22 15:43:32
 * 
 */



# 加载conn.config.php
include 'conn.config.php';

//1. 连接数据库,获取PDO操作对象
function connectPDO($dbType, $host, $dbName, $user, $pass)
{
    //定义全局变量,这样每个function都可以用到
    global $pdoObj; 
    //调用 conn.config.php 连接数据库服务器
    $pdoObj = connMySQL($dbType, $host, $dbName, $user, $pass);
}

//定义 `SELECT` 语句的函数

/**
 * 输出 查询结果 和 结果数
 *
 * @param string $tableName //表名
 * @param string $fields    //字段名
 * @param string $where     //条件
 * @param string $order     //排序
 * @param string $limit     //限制
 * @return [关联数组] 结果集 和 查询到的记录数
 */
function select(string $tableName, string $fields = '*', string $where = '', string $order = '', string $limit = '')
{
    try {

       


        // 1. 组装SQL语句
        $sql = 'SELECT '; // 组装select关键词

        // 2. 组装 查询字段
        if (!empty($fields) && isset($fields)) {
            $sql .= $fields;
        }

        // 3. 组装 FROM 关键字
        $sql .= ' FROM ';

        // 4. 组装 表名
        if (!empty($tableName) && isset($tableName)) {
            $sql .= $tableName;
        } else {
            echo '没有输入表名,退出程序!...';
            exit;
        }

        // 5. 组装 WHERE
        if (!empty($where) && isset($where)) {
            $sql .= ' WHERE ' . $where;
        }

        // 6. 组装 ORDER
        if (!empty($order) && isset($order)) {
            $sql .= ' ORDER BY ' . $order;
        }

        // 7. 组装 LIMIT
        if (!empty($limit) && isset($limit)) {
            $sql .= ' LIMIT ' . $limit;
        }

        // 8. 返回整条sql语句
        //return $sql ;


        $GLOBALS['pdoObj'] ->beginTransaction();  //开启事务处理
        // 返回查询到的结果集 到PDOStatement对象  = 全局$pdo对象 ->query(sql语句)
        $results = $GLOBALS['pdoObj']->query($sql);

        if ($results && $results->rowCount()) {
            // 设置读取模式
            $results->setFetchMode(PDO::FETCH_ASSOC);
            // 一次性把结果集保存在 `关联数组` 里面
            $rows = $results->fetchAll();
            // 统计结果集的总数
            $rowsCount = $results->rowCount();
            // 输入结果集和结果集总数
            $returnResults = [$rows, 'rowsCount' => $rowsCount];
            // // 返回关联数组的结果集
            return $returnResults;
        }
    } catch (PDOException $e) {
        $GLOBALS['pdoObj'] ->rollBack();  //回滚事务处理
        //抛出错误
        die('操作失败:' . $e->getMessage());
    }

}


/**
 * 插入操作
 *
 * @param string $tableName #表名
 * @param array $keysValues #字段名=>字段值 的索引数组
 * @return void
 */
function insert(string $tableName, array $keysValues)
{
    try {
        //1. 组装 INSERT 关键字
        $insertSQL = 'INSERT INTO ';
        //INSERT INTO `表名` SET 字段名=字段值,字段名=字段值
        //2. 组装表名
        $insertSQL .= '`' . trim($tableName) . '`';
        //3. 组装 SET 关键字
        $insertSQL .= ' SET ';
        //4. 拼装需要插入字段名和字段值,类型为关联数组
        foreach ($keysValues as $key => $value) {
            $insertSQL .= '`' . $key . '`' . '=' . "'" . $value . "'" . ',';
        }

        //去掉最右边的','
        $insertSQL = rtrim($insertSQL, ',');
        echo $insertSQL;

        //开启事务处理
        $GLOBALS['pdoObj'] ->beginTransaction();  

        //5. 执行插入操作
        //  返回受影响行数  = $pdo对象 ->exec(sql语句)
        $affectNum = $GLOBALS['pdoObj']->exec($insertSQL);

        //6. 返回刚插入记录的id = $pdo ->lastInsertId()
        $insertId = $GLOBALS['pdoObj']->lastInsertId();

        //7. 组装返回结果, 返回受影响记录数 和 插入的id号
        $returnInsert = ['affectNum' => $affectNum, 'insertId' => $insertId];
        return $returnInsert;

    } catch (PDOException $e) {
        //回滚事务
        $GLOBALS['pdoObj'] ->rollback();
        //抛出错误
        die('操作失败:' . $e->getMessage());
    }

}


function update(string $tableName, array $keysValues,string $where='')
{
    try {
        //1. 组装 UPDATE 关键字
        $updateSQL = 'UPDATE ';
        //UPDATE `表名` SET 字段名=字段值,字段名=字段值 WHERE 条件
        //2. 组装表名
        $updateSQL .= '`' . trim($tableName) . '`';
        //3. 组装 SET 关键字
        $updateSQL .= ' SET ';
        //4. 拼装需要插入字段名和字段值,类型为关联数组
        foreach ($keysValues as $key => $value) {
            $updateSQL .= '`' . $key . '`' . '=' . "'" . $value . "'" . ',';
        }

        //去掉最右边的','
        $updateSQL = rtrim($updateSQL, ',');

        //5. 组合WHERE关键字
        $updateSQL .= ' WHERE ';

        //6. 组合 where 条件
        $updateSQL .= trim($where);

        echo $updateSQL;

        //开启事务处理
        $GLOBALS['pdoObj'] ->beginTransaction();  

        //5. 执行插入操作
        //  返回受影响行数  = $pdo对象 ->exec(sql语句)
        $affectNum = $GLOBALS['pdoObj']->exec($updateSQL);


        //6. 组装返回结果, 返回受影响记录数
        $returnUpdate = ['affectNum' => $affectNum];
        return $returnUpdate;

    } catch (PDOException $e) {
        //回滚事务
        $GLOBALS['pdoObj'] ->rollback();        
        //抛出错误
        die('操作失败:' . $e->getMessage());
    }

}

function delete(string $tableName , string $where='')
{
    // DELETE FROM `表名` WHERE 条件;
    try {
        //1. 组装 DELETE 关键字
        $deleteSQL = 'DELETE FROM ';
        //2. 组装表名
        $deleteSQL .= '`' . trim($tableName) . '`';

        //3. 组合WHERE关键字
        $deleteSQL .= ' WHERE ';

        //4. 组合 where 条件
        $deleteSQL .= trim($where);

        echo $deleteSQL;

        //开启事务处理
        $GLOBALS['pdoObj'] ->beginTransaction();  


        //5. 执行删除操作
        //  返回受影响行数  = $pdo对象 ->exec(sql语句)
        $affectNum = $GLOBALS['pdoObj']->exec($deleteSQL);


        //6. 组装返回结果, 返回受影响记录数
        $returnUpdate = ['affectNum' => $affectNum];
        return $returnUpdate;

    } catch (PDOException $e) {
        //回滚事务
        $GLOBALS['pdoObj'] ->rollback();        
        //抛出错误
        die('操作失败:' . $e->getMessage());
    }

}



/**
 * TODO : 未完成的 SWITCH 操作
 * SEE : https://www.cnblogs.com/xiaoliwang/p/7963471.html
 *
 * @param string $dmlString
 * @param string $tableName
 * @param string $fieldName
 * @param string $fieldValue
 * @param string $where
 * @return void
 */


/**
 * 销毁 PDO 对象
 * @return void
 */
function clearPDO()
{
    //释放PDO对象
    unset($pdoObj);
}


posted @ 2019-03-22 15:53  PaulSpeaking  阅读(511)  评论(0编辑  收藏  举报