TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码
/
注册
用户名
邮箱
文章目录

PHP面向对象封装MySQL操作函数、文件上传

2021-01-04
/
0 评论
/
89 阅读
/
正在检测是否收录...
01/04

Mysql.class.php

<?php
abstract class aDB
{
    abstract public function conn();
    abstract public function query($sql);
    abstract public function getAll($sql);
    abstract public function getRow($sql);
    abstract public function getOne($sql);
    abstract public function exec($data, $table, $act = 'insert', $where = '0');
    abstract public function lastId();
    abstract public function affectRows();
}

class Mysql extends aDB
{
    public $link;

    public function __construct()
    {
        $this->conn();
    }

    /**
     * 连接数据库,从配置文件读取配置信息
     */
    public function conn()
    {
        $cfg = require 'config.php';
        $this->link = new mysqli($cfg['host'], $cfg['name'], $cfg['password'], $cfg['databaseName'], $cfg['port']);
        $this->query('set names ' . $cfg['charset']);
    }

    /**
     * 发送query查询
     * @param string $sql sql语句
     * @return mixed
     */
    public function query($sql)
    {
        return $this->link->query($sql);
    }

    /**
     * 查询多行数据
     * @param string $sql sql语句
     * @return array
     */
    public function getAll($sql)
    {
        $res = $this->query($sql);
        $data = [];
        while ($row = $res->fetch_assoc()) {
            $data[] = $row;
        }
        return $data;
    }

    /**
     * 查询单行数据
     * @param string $sql sql语句
     * @return array
     */
    public function getRow($sql)
    {
        $res = $this->query($sql);
        return $res->fetch_assoc();
    }

    /**
     * 查询单个数据
     * @param string $sql sql语句
     * @return array mixed
     */
    public function getOne($sql)
    {
        $res = $this->query($sql);
        return $res->fetch_row()[0];
    }

    /**
     * 自动创建sql语句并执行
     * @param string $table 表名字
     * @param array $data 关联数组 键/值与表的列/值对应
     * @param string $act 动作/update/insert
     * @param string $where 条件,用于update
     *
     */
    public function exec($table, $data, $act = 'insert', $where = '0')
    {

        if ($act == 'insert') {
            //插入语句 insert into 表名 (字段1,字段2) values ('values1','values2')
            $sql = "insert into $table (";
            $sql .= implode(',', array_keys($data)) . ')';
            $sql .= " values ('";
            $sql .= implode("','", array_values($data)) . "')";
        } else {
            //修改语句 update 表名 set 字段1='values1',字段2='values2' where id=1
            $sql = "update $table set ";
            foreach ($data as $k => $v) {
                $sql .= $k . '=' . "'$v',";
            }
            $sql = rtrim($sql, ',');
            $sql .= " where $where";
        }
        return $this->query($sql);
    }

    /**
     * 返回上一条insert语句产生的主键值
     */
    public function lastId()
    {
        return $this->link->insert_id;
    }

    /**
     * 返回上一条语句影响的行数
     */
    public function affectRows()
    {
        return $this->link->affected_rows;
    }
}

Upload.class.php

<?php
abstract class AUpload
{
    public $allowext = array('jpg', 'jpeg', 'png', 'rar');
    public $maxsize = 1;
    protected $error = '';

    abstract public function getInfo($name);
    abstract public function createDir();
    abstract public function randStr($len = 8);
    abstract protected function checkType($ext);
    abstract protected function checkSize($size);
    abstract public function up($name);

    public function getError()
    {
        return $this->error;
    }
}

class Upload extends AUpload
{
    /**
     * 分析$_FILES中$name域的信息,比如$_FILES['pic']
     * @param string $name 表单中的file里的name值
     * @return array 上传文件的信息
     */
    public function getInfo($name)
    {
        return $_FILES[$name];
    }

    /**
     * 创建目录 /upload/2021/01/04
     * @return string 目录路径
     */
    public function createDir()
    {
        $dir = '/upload/' . date('Y/m/d');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        return $dir;
    }

    /**
     * 生成随机字符串
     * @param int $len 随机字符串的长度
     * @return string 返回生成的字符串
     */
    public function randStr($len = 6)
    {
        $str = str_shuffle('abcedfghjkmnpqrstuvwxyzABCEDFGHJKMNPQRSTUVWXYZ0123456789');
        return substr($str, 0, $len);
    }

    /**
     * 检查文件类型
     * @param $ext 文件后缀
     * @return boolean
     */
    protected function checkType($ext)
    {
        return in_array($ext, $this->allowext);
    }

    /**
     * 检测文件大小
     * @param $size 文件大小
     * @return boolean
     */
    protected function checkSize($size)
    {
        return $size < $this->maxsize * 1024 * 1024;
    }

    /**
     * 上传文件
     * @param string $name 表单中file的name值
     * @return string 上传的文件,如/upload/2021/01/04/1609749834kfyzXr.jpg
     */
    public function up($name)
    {
        if (!isset($_FILES[$name])) {
            echo '没有上传文件';exit();
        }
        $info = $this->getInfo($name);

        $ext = ltrim(strrchr($info['name'], '.'), '.');
        if (!$this->checkType($ext)) {
            echo '不允许上传此类型文件';exit();
        }

        if (!$this->checkSize($info['size'])) {
            echo '文件过大';exit();
        }

        $dir = $this->createDir();
        $filename = time() . $this->randStr() . '.' . $ext;
        if (move_uploaded_file($info['tmp_name'], $dir . '/' . $filename)) {
            $data['path'] = $dir;
            $data['filename'] = $filename;
            return $data;
        } else {
            echo '上传失败';
        }
    }
}

$file = new Upload();
var_dump($file->up('pic'));

upload.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>上传</title>
</head>

<body>
    <form action="Upload.class.php" method="post" enctype="multipart/form-data">
        <input type="file" name="pic">
        <button type="submit" id="submit">提交</button>
    </form>

</body>

</html>

config.php

<?php
return array(
    'host' => 'localhost',
    'name' => 'cs',
    'password' => '123456',
    'databaseName' => 'cs',
    'port' => '3306',
    'charset' => 'utf8'
);

使用方法

$mysql = new Mysql();

1、增

$art['title'] = trim($_POST['title']);
$art['cat_id'] = trim($_POST['cat_id']);
$art['content'] = trim($_POST['content']);
$art['pubtime'] = time();
if ($mysql->exec('art', $art)) {
        echo('添加成功');
    } else {
        echo('添加失败');
    }

2、删

$sql = "delete from cat where cat_id='$cat_id'";
if ($mysql->query($sql)) {
    echo('删除成功');
} else {
    echo('删除失败');
}

3、改

$cat_id = $_GET['cat_id'];
$cat['catname'] = trim($_POST['catname']);
if ($mysql->exec('cat',$cat,'update',"cat_id=$cat_id")) {
    echo('修改成功');
} else {
    echo('修改失败');
}

4、查
查询多行数据

$sql = "select * from cat";
$arr = $mysql->getAll($sql);
print_r($arr);

取出一行数据

$sql = "select * from cat where cat_id='$cat_id'";
if (!$mysql->getRow($sql)) {
    echo('栏目不存在');
    exit();
}

查询返回一个结果

$sql = "select * from cat where cat_id='$cat_id'";
echo $mysql->getOne($sql);

获取上一步insert 操作产生的主键id

$mysql->lastId();
经验PHPMySQL封装函数文件上传面向对象
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwll.cn/archives/4997/(转载时请注明本文出处及文章链接)

评论 (0)