php写一个数据表复制的函数,刚开始写哈(pdo方式):

164 阅读1分钟
/**
     * 复制数据表
     * @param $sourceTable string 源表,如mc_member
     * @param $newTable string 新表名称,如mc_member_copy
     * @param string $where 复制的条件限制
     * @param bool $isForce 是否强制执行,如果为true则存在时先删除后重新复制
     * @return array
     */
    public function cp_db($sourceTable, $newTable, $where = '',$isForce = false)
    {
        $stime = microtime(true);
        //为了更好你用索引复制,where条件必须完整匹配
        if (!empty($where) && (stripos($where, 'where') === false||stripos($where, 'WHERE') === false)) {
            return ['code' => 400, 'message' => 'where 条件非法,必须带上where关键词'];
        }

        if (pdo_tableexists($newTable)) {
            if ($isForce){
                //存在时先删除后复制
                pdo_run(" DROP TABLE IF EXISTS ".tablename($newTable).";");
                if (pdo_tableexists($newTable)){
                    return ['code' => 400, 'message' => $newTable . ' 强制删除失败!'];
                }
            }else{
                return ['code' => 400, 'message' => $newTable . '已存在'];
            }
        }

        //先把结构复制,然后复制数据
        pdo_run('create table ' . tablename($newTable) . ' like ' . tablename($sourceTable) . ';');

        if (!pdo_tableexists($newTable)) {
            return ['code' => 400, 'message' => $newTable . '创建失败:'.pdo_tableexists($newTable)];
        }
        //开始复制
        pdo_run('insert into ' . tablename($newTable) . ' select * from ' . tablename($sourceTable). $where);
        
        $has = pdo_tableexists($newTable);

        return ['status' => $newTable,'time'=>microtime(true)-$stime];
    }