Home  >  Article  >  Backend Development  >  How to delete the database and files uploaded to the server at the same time in thinkphp5

How to delete the database and files uploaded to the server at the same time in thinkphp5

不言
不言Original
2018-08-11 17:06:222286browse

The content of this article is about how to delete the database and upload the files to the server at the same time in thinkphp5. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

How to delete the database and the files uploaded to the server at the same time in TP5:

The method defined in the model is as follows

<?php

namespace app\admin\model;
use think\Model;

class Pic extends Model
{ 
  
	public function unlink($path)
	{
		return  is_file($path) && unlink($path);
	}

}

Then call yours in the controller method, it is recommended to use absolute path for $path in the controller,

Introduce space class elements into the controller:

use think\File;
use app\admin\model\Pic as PicModel;//防止类名字重复报错,起一个别名

Then instantiate it in the method, and then call the method:

             public function del()
	    {		
	       $id=input(&#39;id&#39;);//返回的结果为获取的id
	       $lunbotu=db(&#39;lunbotu&#39;)->find($id);//获取一条数据,这里可以dump()数据,返回结果为数组,访问数组中文件的存放信息的字段,这里是Pic
	       $path=&#39;../public/static/uploads/&#39;.$lunbotu[&#39;Pic&#39;];//定义文件存放的路径
	       $unlink=new PicModel();//实例化
		if($unlink->unlink($path) && db(&#39;lunbotu&#39;)->delete(input(&#39;id&#39;)))
		{
		    return redirect(&#39;pic&#39;);//重定向到你想要的界面
		}
		else
		{
	        	$this->error(&#39;删除轮播图失败&#39;);
		}
	    }

Related recommendations:

Analysis of iterators and generators in PHP and introduction to their advantages and disadvantages

##thinkphp5 belongsToMany() module name Solving the naming problem

The above is the detailed content of How to delete the database and files uploaded to the server at the same time in thinkphp5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn