thinkphp6操作数据库——判断数据表、字段是否存在,添加、修改、删除字段

文章介绍了如何在ThinkPHP6框架下开发在线更新功能,包括检查数据表和字段是否存在、添加和删除字段以及修改字段的PHP方法,旨在简化网站更新过程,提高用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前使用thinkphp6写了一个网站,但是没有写后台在线更新的功能,每次更新都需要下载新的文件覆盖,数据表还得自己手动创建,给没有相关知识的人去使用就会比较难,所以我决定开发一个在线更新的功能。

封装了一些操作数据表的方法,方便创建和修改数据表字段,代码如下:

  • 判断数据表是否存在
   public function check_table($table){
        $res = Db::query('SHOW TABLES LIKE '."'".$table."'");
        if($res){
            return 1;
        }else{
            return 0;
        }
    }
  •     判断字段是否存在

   public function check_column($table,$column){
        $res = Db::query('select count(*) from information_schema.columns where table_name = '."'".$table."' ". 'and column_name ='."'".$column."'");
        if($res[0]['count(*)'] != 0){
            return 1;
        }else{
            return 0;
        }
    }
  •     添加字段

    public function add_column($table,$column,$type,$condition,$after){
        $res = Db::execute('alter table'." `".$table."` ".'add'." `".$column."` ".$type." ".$condition." ".'after'." `".$after."`");
        if($res){
            return 1;
        }else{
            return 0;
        }
    }
  •     删除字段

    public function del_column($table,$column){
        $res = Db::execute('alter table '."`".$table."`".' drop column'."`".$column."`");
        if($res){
            return 1;
        }else{
            return 0;
        }
    }
  •     修改字段

 public function update_column($table,$old_column,$column,$type){
        //字段名和类型同时修改才会返回1不然返回0
        $res = Db::execute('alter table' ." `".$table."` ". 'change' ." `".$old_column."` " ."`".$column."`" .$type);
        if($res){
            return 1;
        }else{
            return 0;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

创梦流浪人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值