<?php
	require("__include-common.php");
	require("../account/__logincheck.php");
	if ($_SESSION['システム管理者'] <> "YES") {
		exit;
	}
	if (DB_TOOL_ID_PASSWORD_USE == 'YES') {
		require("../id-manager/__include-im-login.php");
		require("../id-manager/im-logincheck.php");
	}
	if (($dbname = $_GET['db']) == '') {
		error_exit('データベース名なし');
	}
	if (($tblname = $_GET['tb']) == '') {
		error_exit('テーブル名なし');
	}
	$omit_col = $_GET['col'].'';
	$fields = get_table_field($dbname, $tblname);
	put_table_list($dbname, $tblname, $fields, $omit_col);
function get_table_field($dbname, $tblname) {
	$con = @mysql_connect(_DB_SERVER, _DB_SCHEMA_USERNAME, _DB_SCHEMA_PASSWORD);
	if ($con == False) {
		error_exit('データベース接続エラー');
	}
	mysql_query('set names utf8', $con);
	if (!mysql_select_db($dbname)) {
		error_exit('データベース選択エラー');
	}
	$rs = mysql_query('desc '.$tblname);
	if (!$rs) {
		error_exit ($tblname.'：テーブル選択エラー');
	}
	$fields = array();
	while ($rec = mysql_fetch_array($rs)) {
		$fields[] = array($rec['Field'], $rec['Type']);
	}
	$con = mysql_close($con);
	return $fields;
}
function put_table_list($dbname, $tblname, $fields, $omit_col) {
	$colname = '';
	foreach ($fields as $field) {
		if ($colname <> '') $colname .= ',';
		$colname .= $field[0];
	}
	$sql = 'select ' . $colname . ' from ' . $tblname;
	$con = @mysql_connect(_DB_SERVER, _DB_SCHEMA_USERNAME, _DB_SCHEMA_PASSWORD);
	if ($con == False) {
		error_exit('データベース接続エラー');
	}
	mysql_query('set names utf8', $con);
	if (!mysql_select_db($dbname)) {
		error_exit('データベース選択エラー');
	}
	header("Content-type: text/csv\n");
	header("Content-disposition: filename=".$dbname.'-'.myfile_ENCODE($tblname).".csv\n");
	$sw = False;
	foreach ($fields as $field) {
		if ($field[0] <> $omit_col) {
			if ($sw) {
				echo ',';
			} else {
				$sw = True;
			}
			echo '"'.myfile_ENCODE($field[0]).'"';
		}
	}
	echo "\n";
	$rs = my_mysql_query($sql);
	while ($rec=mysql_fetch_array($rs)) {
		$sw = False;
		foreach ($fields as $field) {
			if ($field[0] <> $omit_col) {
				if ($sw) {
					echo ',';
				} else {
					$sw = True;
				}
				if (stripos($field[1],'int') !== False or stripos($field[1],'decimal') !== False or stripos($field[1],'float') !== False or stripos($field[1],'double') !== False) {
					echo $rec[$field[0]];
				} else {
					echo '"'.myfile_ENCODE(str_replace("\\","\\\\",str_replace('"','""',$rec[$field[0]]))).'"';
				}
			}
		}
		echo "\n";
	}
	$con = mysql_close($con);
}
?>
