Use PHP to export MySQL data table structure and SQL files

Table of contents

1. Obtain all data tables in the database

Method 1: TP5

Method 2: Native PHP

2. Export the data structure of the specified data table

3. Export SQL file

4. Generate SQL statements 

5. Complete code

front end

rear end


Language: PHP

Database: MySQL

Function: Divided into four parts, ① find all tables in the database; ② export the structure of the specified data table; ③ export the data of the specified data table in the form of SQL files, and supports conditional export, and the exported data can be directly imported into the database; ④ Generate SQL statements.

overall effect:

1. Obtain all data tables in the database

Method 1: TP5

Using the getTables method in TP5's DB class

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

Method 2: Native PHP

You can also use native PHP code

// 数据库信息
$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");

2. Export the data structure of the specified data table

Logical description: Enter the data table to be exported, specify the export file name, obtain the data structure, and write the export file

// 导出数据结构
	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);

	}

The result after export is as shown below, which can be directly imported into the database for use.

3. Export SQL file

Note: Export the data of the specified data table in the form of a SQL file, and support conditional export. The exported data can be directly imported into the database.

① First enter the exported data table and conditions (the conditions can be empty), and specify the export file name;

② Get the structure of the data table and write it to the file

③ Assemble SQL statements according to the input conditions and query

④ After receiving the query results, loop the result set and splice and insert the data format (if there is a special format, please filter it out, otherwise an error will occur when importing into the database)

⑤ Write export file

It should be noted that in the input condition part, the field name can be written normally, and the expression supports =;>;<;>=;<=;<>;like;[not] between;[not] in;[not] null. Of course, other expressions can also be supported. Here are only the expressions that have been tested and can be used. The query conditions need special attention. Different expressions correspond to different query conditions. For example, like corresponds to "%ultrasound%" ", between corresponds to 1 AND 8, which is actually the writing method of native SQL, spliced ​​through a custom method.

code show as below

	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);
		}

	}

The export results are as follows. You can use this file to directly import into other databases.

4. Generate SQL statements 

Description: Receive the input data table and conditions, construct the SQL query statement, and return the constructed statement

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;
	}

The effect is as follows

  

5. Complete code

front end

<!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>

rear end

<?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;
	}


}

If there are other expressions that have been tested and can be used, you can leave a message below. If errors occur when the exported SQL file is imported into other databases, your advice is also welcome.

Guess you like

Origin blog.csdn.net/qq_25285531/article/details/130989854