[PHP]MySQL Temporary Table

function create_tmp_table($tmp_table,$tmp_col){
	drop_tmp_table($tmp_table); // 使用前先刪除
	$sql_str = '';
	foreach($tmp_col AS $k => $v){
		$sql_str .= "$k $v,";
	}
	$sql = "CREATE TEMPORARY TABLE $tmp_table ( 
			ID INT NOT NULL AUTO_INCREMENT,
			$sql_str
			tmp_create_time datetime,
			PRIMARY KEY(ID)
		)"; //建立暫存table
	$result  = mysqli_query($conn,$sql);
}

function ins_tmp_table($tmp_table,$arr){
	foreach($arr AS $k => $v){
		$sql_str .= "$k = '$v',";
	}
	$sql = "INSERT INTO $tmp_table  SET $sql_str tmp_create_time = NOW()";
	$result  = mysqli_query($conn,$sql);
}

function drop_tmp_table($tmp_table){
	$sql = "DROP TEMPORARY TABLE IF EXISTS $tmp_table "; 
	$result  = mysqli_query($conn,$sql);
}
$tmp_table = 'tmp_tablename'; // 前面要加 tmp_,避免誤刪正式table
$tmp_col = array( // 設定欄位
	'col1' => 'varchar(20)',
	'col2' => 'varchar(10)',
	'the_time' => 'datetime'
);

$arr[col1] = 'hello';
$arr[col2] = 'world';
$arr[the_time] = 2019-01-01 00:00:00;
ins_tmp_table($tmp_table,$arr); // 寫入臨時表
/*
SELECT * FROM tmp_table 
*/
drop_tmp_table($tmp_table); // 用完記得要刪除