利用PHP导出MySQL数据表结构和SQL文件

目录

一、获取数据库所有的数据表

方法一:TP5

方法二:原生PHP

二、导出指定数据表的数据结构

三、 导出SQL文件

四、生成SQL语句 

五、完整代码

前端

后端


语言:PHP

数据库:MySQL

功能:分为四部分,① 查出数据库的所有表;② 导出指定数据表的结构;③ 以SQL文件的形式导出指定数据表的数据,并且支持带条件导出,导出的数据可以直接导入数据库;④ 生成SQL语句。

整体效果:

一、获取数据库所有的数据表

方法一:TP5

使用TP5的DB类中的getTables方法

public function index()
	{
		//获取数据库所有的数据表
		$tabList = Db::getTables();		
		$this->assign(['tabList'=>$tabList]);
		return $this->fetch();
	}

方法二:原生PHP

也可以使用原生PHP代码

// 数据库信息
$cfg_dbhost = 'localhost';
$cfg_dbname = 'xxx';
$cfg_dbuser = 'XXX';
$cfg_dbpwd = 'xxx';
$cfg_db_language = 'utf8';
$to_file_name = "xxx.sql"; //导出文件名

//链接数据库
$link = mysqli_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd,$cfg_dbname);

//查询数据库中所有表名,并保存在数组中
$tables = mysqli_query($link,"SHOW TABLES");

二、导出指定数据表的数据结构

逻辑说明:输入要导出的数据表,指定导出的文件名,获取数据结构,写入导出文件

// 导出数据结构
	public function downStru()
	{
		// 接收条件
		$table = input('table');
		$to_file_name = ROOT_PATH . "public". DS ."sql". DS . "table_".$table.".sql" ; // 导出文件名

		// 导出数据表结构
		$sql = "show create table ".$table;
		$res = Db::query($sql);
		$info = "-- ----------------------------\r\n";
	    $info .= "-- Table structure for `".$table."`\r\n";
	    $info .= "-- ----------------------------\r\n";
	    $info .= "DROP TABLE IF EXISTS `".$table."`;\r\n";
	    $sqlStr = $info.$res[0]['Create Table'].";\r\n\r\n";

	    // 写入到文件
	    file_put_contents($to_file_name,$sqlStr);

	}

导出后结果如下图,可以直接导入数据库使用

三、 导出SQL文件

说明:以SQL文件的形式导出指定数据表的数据,并且支持带条件导出,导出的数据可以直接导入数据库。

① 先输入到导出的数据表和条件(条件可为空),指定导出文件名称;

② 获取数据表的结构并写入文件

③ 根据输入的条件组装SQL语句,并查询

④ 接收到查询结果后,循环结果集并拼接插入数据格式(如果有特殊格式请过滤掉,否则在导入数据库时会出错)

⑤ 写入导出文件

需要注意的是输入条件部分,字段名可以正常写,表达式支持=;>;<;>=;<=;<>;like;[not] between;[not] in;[not] null几种,当然也可以支持其他表达式,这里只列出了已经测试可以使用的表达式,查询条件需要特别注意,不同的表达式对应的查询条件也不相同,比如说like对应的是"%超声%",between对应的是1 AND 8,其实就是原生SQL的写法,通过自定义的方法进行拼接。

代码如下

	public function downSql()
	{	
		// ① 接收条件
		$table = input('table');
		$field = input('field');
		$expre = input('expre');
		$condition = input('condition');

		$to_file_name = ROOT_PATH . "public". DS ."sql". DS . "table_".$table.".sql" ; // 导出文件名

		/**********② 导出数据表结构**************/
		$sql = "show create table ".$table;
		$res = Db::query($sql);
		$info = "-- ----------------------------\r\n";
	    $info .= "-- Table structure for `".$table."`\r\n";
	    $info .= "-- ----------------------------\r\n";
	    $info .= "DROP TABLE IF EXISTS `".$table."`;\r\n";
	    $sqlStr = $info.$res[0]['Create Table'].";\r\n\r\n";
		file_put_contents($to_file_name,$sqlStr);

		
		/**********导出数据**************/
		// ③ 根据输入条件组装查询条件
		if (!empty($field) && !empty($expre) && !empty($condition)) {

			$where = "where"." ". $field . " " .$expre . " " .$condition;
			// 查询语句
			$sql = "select * from ".$table ." ".$where;
		}else{
			// 查询语句
			$sql = "select * from ".$table ;
		}
		$res = Db::query($sql);

		// 判断数据是否为空
		if(count($res) >= 1){
			$info = "-- ----------------------------\r\n";
			$info .= "-- Records for `".$table."`\r\n";
			$info .= "-- ----------------------------\r\n";
			file_put_contents($to_file_name,$info,FILE_APPEND);

			/**********④ 拼接插入数据格式**************/
			 foreach($res as $v){
			 	$sqlStr = "INSERT INTO `".$table."` VALUES (";

			 	// 循环出字段对应的数据,并组装
			 	foreach($v as $zd){

			 		// 替换数据中的换行符
		            $zd = str_replace("\r\n","",$zd);
		            $sqlStr .= "'".$zd."', ";
		        }

		        //去掉最后一个逗号和空格
		        $sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
		        $sqlStr .= ");\r\n";
		        // ⑤ 写入文件
		        file_put_contents($to_file_name,$sqlStr,FILE_APPEND);

			 }

			 file_put_contents($to_file_name,"\r\n",FILE_APPEND);
		}

	}

导出结果如下,可以使用此文件直接导入到其他数据库

四、生成SQL语句 

说明:接收输入的数据表和条件,构造SQL查询语句,把构造的语句返回

public function creatSql()
	{
		// 接收条件
		$table = input('table');
		$field = input('field');
		$expre = input('expre');
		$condition = input('condition');

		// 根据输入条件组装查询条件
		if (!empty($field) && !empty($expre) && !empty($condition)) {

			$where = "where"." ". $field . " " .$expre . " " .$condition;
			// 查询语句
			$sql = "select * from ".$table ." ".$where;
		}else{
			// 查询语句
			$sql = "select * from ".$table ;
		}

		return $sql;
	}

效果如下

  

五、完整代码

前端

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
	<link rel="stylesheet" type="text/css" href="/static/index/layui/css/layui.css">
  	<script type="text/javascript" src="/static/index/layui/layui.js"></script>
	<script src="/static/index/js/jquery-1.11.3.min.js"></script>

	<style type="text/css">
		body{
	  		background-color:#F7F7F7;
	  		-webkit-overflow-scrolling: touch;
	  		height:auto;
	  		margin:0 auto;
	  		margin-top: 0.5rem;
	  	}
	</style>
</head>

<body>
<div style="width:80%; margin: 1rem auto; background: #fff;padding:0.5rem">

	<div class="layui-row layui-col-space30">
    	<div class="layui-col-xs4 layui-col-sm4 layui-col-md4">
    		
			<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
			  <legend>数据表</legend>
			</fieldset>
			<table class="layui-table">
			    <thead>
			      <tr>
			        <th>数据表</th>
			      </tr> 
			    </thead>
			    <tbody>
		      	{volist name="tabList" id="vo"}
			      <tr>
					<td>{$vo}</td>
			      </tr>
				{/volist}
			    </tbody>
			</table>
    	</div>
    	<div class="layui-col-xs8 layui-col-sm8 layui-col-md8">
    		<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
			  <legend>导出数据结构</legend>
			</fieldset>
			<div class="layui-form-item">
			    <label class="layui-form-label">输入表名</label>
			    <div class="layui-input-block">
			      <input type="text" name="table1" lay-verify="required" autocomplete="off" placeholder="数据表" class="layui-input">
			    </div>
			</div>
			<div class="layui-form-item">
			    <div class="layui-input-block">
					<button type="button" class="layui-btn layui-btn-normal structure" style="margin-bottom:0.2rem;">导出数据结构</button>
			    </div>
			</div>

    		<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
			  <legend>导出SQL文件</legend>
			</fieldset>
			<div class="layui-form-item">
			    <label class="layui-form-label">输入表名</label>
			    <div class="layui-input-block">
			      <input type="text" name="table2" lay-verify="required" autocomplete="off" placeholder="数据表" class="layui-input">
			    </div>
			</div>
			<div class="layui-form-item">
			    <label class="layui-form-label">字段名</label>
			    <div class="layui-input-block">
			      <input type="text" name="field" lay-verify="" autocomplete="off" placeholder="字段" class="layui-input">
			    </div>
			</div>

			<div class="layui-form-item">
			      <label class="layui-form-label">表达式</label>
			      <div class="layui-input-block">
			        <input type="text" name="expre" lay-verify="" autocomplete="off" class="layui-input">
			      </div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label" style="color:#999">说明:</label>
			    <div class="layui-form-mid layui-word-aux"> =;>;<;>=;<=;<>;like;[not]between;[not]in;[not]null</div>
			</div>
			<div class="layui-form-item">
			      <label class="layui-form-label">查询条件</label>
			      <div class="layui-input-block">
			        <input type="text" name="condition" lay-verify="" autocomplete="off" class="layui-input" placeholder="数值或文本">
			      </div>
			      <div class="layui-form-mid layui-word-aux"></div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label" style="color:#999">说明:</label>
			    <div class="layui-form-mid layui-word-aux"> 字符串需要加英文引号['字符串'];like需要加%[字符串%];between使用[1 AND 8]形式;in 使用[(1,8)]形式</div>
			</div>

			<div class="layui-form-item">
			    <div class="layui-input-block">
					<button type="button" class="layui-btn layui-btn-normal creatSql" style="margin-bottom:0.2rem;">生成SQL语句</button>
					<button type="button" class="layui-btn layui-btn-normal downSql" style="margin-bottom:0.2rem;">导出sql文件</button>
			    </div>
			</div>

			<div class="layui-form-item">
				 <label class="layui-form-label">原生SQL语句</label>
			    <div class="layui-input-block">
					<textarea placeholder="" class="layui-textarea sqltext"></textarea>
			    </div>
			</div>

    	</div>

	</div>
	

	
</div>

</body>

<script type="text/javascript">
	layui.use(['form','element'], function(){
		var form = layui.form
		,$ = layui.jquery
		,element = layui.element;

		// 导出数据结构
		$('.structure').click(function () {

			var table= $("input[name='table1']").val()
			console.log(table)

			$.ajax({
				url:'downStru',
				type:'get',
				dataType:'JSON',
				data:{table:table},
				success:function (res) {
					console.log(res)
				}
			})
		})

		// 导出sql文件
		$('.downSql').click(function () {

			var table= $("input[name='table2']").val()
			console.log(table)
			var field= $("input[name='field']").val()
			var expre= $("input[name='expre']").val()
			var condition= $("input[name='condition']").val()

			$.ajax({
				url:'downSql',
				type:'get',
				dataType:'JSON',
				data:{table:table,field:field,expre:expre,condition:condition},
				success:function (res) {
					console.log(res)
				}
			})
		})

		// 生成SQL语句
		$('.creatSql').click(function () {

			var table= $("input[name='table2']").val()
			console.log(table)
			var field= $("input[name='field']").val()
			var expre= $("input[name='expre']").val()
			var condition= $("input[name='condition']").val()

			$.ajax({
				url:'creatSql',
				type:'get',
				dataType:'JSON',
				data:{table:table,field:field,expre:expre,condition:condition},
				success:function (res) {
					console.log(res)
					$('.sqltext').val(res)
				}
			})
		})
	})
</script>

</html>

后端

<?php
namespace app\index\controller;
use think\Controller;
use think\Db;

/**
 * 数据库操作类
 */
class Sql extends Controller
{

	public function index()
	{
		//获取数据库所有的数据表
		$tabList = Db::getTables();		
		$this->assign(['tabList'=>$tabList]);
		return $this->fetch();
	}

	// 导出数据结构
	public function downStru()
	{
		// 接收条件
		$table = input('table');
		$to_file_name = ROOT_PATH . "public". DS ."sql". DS . "table_".$table.".sql" ; // 导出文件名

		// 导出数据表结构
		$sql = "show create table ".$table;
		$res = Db::query($sql);
		$info = "-- ----------------------------\r\n";
	    $info .= "-- Table structure for `".$table."`\r\n";
	    $info .= "-- ----------------------------\r\n";
	    $info .= "DROP TABLE IF EXISTS `".$table."`;\r\n";
	    $sqlStr = $info.$res[0]['Create Table'].";\r\n\r\n";

	    // 写入到文件
	    file_put_contents($to_file_name,$sqlStr);

	}

	// 导出sql文件
	public function downSql()
	{	
		// ① 接收条件
		$table = input('table');
		$field = input('field');
		$expre = input('expre');
		$condition = input('condition');

		$to_file_name = ROOT_PATH . "public". DS ."sql". DS . "table_".$table.".sql" ; // 导出文件名

		/**********② 导出数据表结构**************/
		$sql = "show create table ".$table;
		$res = Db::query($sql);
		$info = "-- ----------------------------\r\n";
	    $info .= "-- Table structure for `".$table."`\r\n";
	    $info .= "-- ----------------------------\r\n";
	    $info .= "DROP TABLE IF EXISTS `".$table."`;\r\n";
	    $sqlStr = $info.$res[0]['Create Table'].";\r\n\r\n";
		file_put_contents($to_file_name,$sqlStr);

		
		/**********导出数据**************/
		// ③ 根据输入条件组装查询条件
		if (!empty($field) && !empty($expre) && !empty($condition)) {

			$where = "where"." ". $field . " " .$expre . " " .$condition;
			// 查询语句
			$sql = "select * from ".$table ." ".$where;
		}else{
			// 查询语句
			$sql = "select * from ".$table ;
		}
		$res = Db::query($sql);

		// 判断数据是否为空
		if(count($res) >= 1){
			$info = "-- ----------------------------\r\n";
			$info .= "-- Records for `".$table."`\r\n";
			$info .= "-- ----------------------------\r\n";
			file_put_contents($to_file_name,$info,FILE_APPEND);

			/**********④ 拼接插入数据格式**************/
			 foreach($res as $v){
			 	$sqlStr = "INSERT INTO `".$table."` VALUES (";

			 	// 循环出字段对应的数据,并组装
			 	foreach($v as $zd){

			 		// 替换数据中的换行符
		            $zd = str_replace("\r\n","",$zd);
		            $sqlStr .= "'".$zd."', ";
		        }

		        //去掉最后一个逗号和空格
		        $sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
		        $sqlStr .= ");\r\n";
		        // ⑤ 写入文件
		        file_put_contents($to_file_name,$sqlStr,FILE_APPEND);

			 }

			 file_put_contents($to_file_name,"\r\n",FILE_APPEND);
		}

	}

	// 生成SQL语句
	public function creatSql()
	{
		// 接收条件
		$table = input('table');
		$field = input('field');
		$expre = input('expre');
		$condition = input('condition');

		// 根据输入条件组装查询条件
		if (!empty($field) && !empty($expre) && !empty($condition)) {

			$where = "where"." ". $field . " " .$expre . " " .$condition;
			// 查询语句
			$sql = "select * from ".$table ." ".$where;
		}else{
			// 查询语句
			$sql = "select * from ".$table ;
		}

		return $sql;
	}


}

如果有其他已经测试可以使用的表达式可以在下面留言,若导出的SQL文件在导入到其他数据库时出现错误,也欢迎指教。

猜你喜欢

转载自blog.csdn.net/qq_25285531/article/details/130989854
今日推荐